Coverage Report

Created: 2024-07-25 01:20

/src/DLXEmu/external/imgui/imgui.cpp
Line
Count
Source (jump to first uncovered line)
1
// dear imgui, v1.91.0 WIP
2
// (main code and documentation)
3
4
// Help:
5
// - See links below.
6
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7
// - Read top of imgui.cpp for more details, links and comments.
8
9
// Resources:
10
// - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md)
11
// - Homepage ................... https://github.com/ocornut/imgui
12
// - Releases & changelog ....... https://github.com/ocornut/imgui/releases
13
// - Gallery .................... https://github.com/ocornut/imgui/issues/7503 (please post your screenshots/video there!)
14
// - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there)
15
//   - Getting Started            https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code)
16
//   - Third-party Extensions     https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more)
17
//   - Bindings/Backends          https://github.com/ocornut/imgui/wiki/Bindings (language bindings, backends for various tech/engines)
18
//   - Glossary                   https://github.com/ocornut/imgui/wiki/Glossary
19
//   - Debug Tools                https://github.com/ocornut/imgui/wiki/Debug-Tools
20
//   - Software using Dear ImGui  https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui
21
// - Issues & support ........... https://github.com/ocornut/imgui/issues
22
// - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps)
23
24
// For first-time users having issues compiling/linking/running/loading fonts:
25
// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
26
// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
27
28
// Copyright (c) 2014-2024 Omar Cornut
29
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
30
// See LICENSE.txt for copyright and licensing details (standard MIT License).
31
// This library is free but needs your support to sustain development and maintenance.
32
// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
33
// PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Funding
34
// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
35
36
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
37
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
38
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
39
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
40
// to a better solution or official support for them.
41
42
/*
43
44
Index of this file:
45
46
DOCUMENTATION
47
48
- MISSION STATEMENT
49
- CONTROLS GUIDE
50
- PROGRAMMER GUIDE
51
  - READ FIRST
52
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
53
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
54
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
55
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
56
- API BREAKING CHANGES (read me when you update!)
57
- FREQUENTLY ASKED QUESTIONS (FAQ)
58
  - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
59
60
CODE
61
(search for "[SECTION]" in the code to find them)
62
63
// [SECTION] INCLUDES
64
// [SECTION] FORWARD DECLARATIONS
65
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
66
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
67
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
68
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
69
// [SECTION] MISC HELPERS/UTILITIES (File functions)
70
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
71
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
72
// [SECTION] ImGuiStorage
73
// [SECTION] ImGuiTextFilter
74
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
75
// [SECTION] ImGuiListClipper
76
// [SECTION] STYLING
77
// [SECTION] RENDER HELPERS
78
// [SECTION] INITIALIZATION, SHUTDOWN
79
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
80
// [SECTION] ID STACK
81
// [SECTION] INPUTS
82
// [SECTION] ERROR CHECKING
83
// [SECTION] ITEM SUBMISSION
84
// [SECTION] LAYOUT
85
// [SECTION] SCROLLING
86
// [SECTION] TOOLTIPS
87
// [SECTION] POPUPS
88
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
89
// [SECTION] DRAG AND DROP
90
// [SECTION] LOGGING/CAPTURING
91
// [SECTION] SETTINGS
92
// [SECTION] LOCALIZATION
93
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
94
// [SECTION] DOCKING
95
// [SECTION] PLATFORM DEPENDENT HELPERS
96
// [SECTION] METRICS/DEBUGGER WINDOW
97
// [SECTION] DEBUG LOG WINDOW
98
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
99
100
*/
101
102
//-----------------------------------------------------------------------------
103
// DOCUMENTATION
104
//-----------------------------------------------------------------------------
105
106
/*
107
108
 MISSION STATEMENT
109
 =================
110
111
 - Easy to use to create code-driven and data-driven tools.
112
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
113
 - Easy to hack and improve.
114
 - Minimize setup and maintenance.
115
 - Minimize state storage on user side.
116
 - Minimize state synchronization.
117
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
118
 - Efficient runtime and memory consumption.
119
120
 Designed primarily for developers and content-creators, not the typical end-user!
121
 Some of the current weaknesses (which we aim to address in the future) includes:
122
123
 - Doesn't look fancy.
124
 - Limited layout features, intricate layouts are typically crafted in code.
125
126
127
 CONTROLS GUIDE
128
 ==============
129
130
 - MOUSE CONTROLS
131
   - Mouse wheel:                   Scroll vertically.
132
   - SHIFT+Mouse wheel:             Scroll horizontally.
133
   - Click [X]:                     Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
134
   - Click ^, Double-Click title:   Collapse window.
135
   - Drag on corner/border:         Resize window (double-click to auto fit window to its contents).
136
   - Drag on any empty space:       Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
137
   - Left-click outside popup:      Close popup stack (right-click over underlying popup: Partially close popup stack).
138
139
 - TEXT EDITOR
140
   - Hold SHIFT or Drag Mouse:      Select text.
141
   - CTRL+Left/Right:               Word jump.
142
   - CTRL+Shift+Left/Right:         Select words.
143
   - CTRL+A or Double-Click:        Select All.
144
   - CTRL+X, CTRL+C, CTRL+V:        Use OS clipboard.
145
   - CTRL+Z, CTRL+Y:                Undo, Redo.
146
   - ESCAPE:                        Revert text to its original value.
147
   - On OSX, controls are automatically adjusted to match standard OSX text editing 2ts and behaviors.
148
149
 - KEYBOARD CONTROLS
150
   - Basic:
151
     - Tab, SHIFT+Tab               Cycle through text editable fields.
152
     - CTRL+Tab, CTRL+Shift+Tab     Cycle through windows.
153
     - CTRL+Click                   Input text into a Slider or Drag widget.
154
   - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
155
     - Tab, SHIFT+Tab:              Cycle through every items.
156
     - Arrow keys                   Move through items using directional navigation. Tweak value.
157
     - Arrow keys + Alt, Shift      Tweak slower, tweak faster (when using arrow keys).
158
     - Enter                        Activate item (prefer text input when possible).
159
     - Space                        Activate item (prefer tweaking with arrows when possible).
160
     - Escape                       Deactivate item, leave child window, close popup.
161
     - Page Up, Page Down           Previous page, next page.
162
     - Home, End                    Scroll to top, scroll to bottom.
163
     - Alt                          Toggle between scrolling layer and menu layer.
164
     - CTRL+Tab then Ctrl+Arrows    Move window. Hold SHIFT to resize instead of moving.
165
   - Output when ImGuiConfigFlags_NavEnableKeyboard set,
166
     - io.WantCaptureKeyboard flag is set when keyboard is claimed.
167
     - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
168
     - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
169
170
 - GAMEPAD CONTROLS
171
   - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
172
   - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
173
   - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
174
   - Backend support: backend needs to:
175
      - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
176
      - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
177
        Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
178
      - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
179
   - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
180
     with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
181
182
 - REMOTE INPUTS SHARING & MOUSE EMULATION
183
   - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
184
   - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
185
     in order to share your PC mouse/keyboard.
186
   - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
187
   - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
188
     Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
189
     When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
190
     When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
191
     (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
192
     (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
193
     to set a boolean to ignore your other external mouse positions until the external source is moved again.)
194
195
196
 PROGRAMMER GUIDE
197
 ================
198
199
 READ FIRST
200
 ----------
201
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
202
 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
203
   The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
204
   data retention on your side, less state duplication, less state synchronization, fewer bugs.
205
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
206
   Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
207
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
208
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
209
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
210
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
211
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
212
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
213
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
214
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
215
   If you get an assert, read the messages and comments around the assert.
216
 - This codebase aims to be highly optimized:
217
   - A typical idle frame should never call malloc/free.
218
   - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
219
   - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
220
     Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
221
 - This codebase aims to be both highly opinionated and highly flexible:
222
   - This code works because of the things it choose to solve or not solve.
223
   - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
224
     and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
225
     This is to increase compatibility, increase maintainability and facilitate use from other languages.
226
   - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
227
     See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
228
     We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
229
   - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
230
     (so don't use ImVector in your code or at our own risk!).
231
   - Building: We don't use nor mandate a build system for the main library.
232
     This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
233
     This is also because providing a build system for the main library would be of little-value.
234
     The build problems are almost never coming from the main library but from specific backends.
235
236
237
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
238
 ----------------------------------------------
239
 - Update submodule or copy/overwrite every file.
240
 - About imconfig.h:
241
   - You may modify your copy of imconfig.h, in this case don't overwrite it.
242
   - or you may locally branch to modify imconfig.h and merge/rebase latest.
243
   - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
244
     specify a custom path for your imconfig.h file and instead not have to modify the default one.
245
246
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
247
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
248
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
249
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
250
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
251
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
252
   likely be a comment about it. Please report any issue to the GitHub page!
253
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
254
 - Try to keep your copy of Dear ImGui reasonably up to date!
255
256
257
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
258
 ---------------------------------------------------------------
259
 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
260
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
261
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
262
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
263
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
264
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
265
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
266
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
267
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
268
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
269
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
270
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
271
272
273
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
274
 --------------------------------------
275
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
276
 The sub-folders in examples/ contain examples applications following this structure.
277
278
     // Application init: create a dear imgui context, setup some options, load fonts
279
     ImGui::CreateContext();
280
     ImGuiIO& io = ImGui::GetIO();
281
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
282
     // TODO: Fill optional fields of the io structure later.
283
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
284
285
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
286
     ImGui_ImplWin32_Init(hwnd);
287
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
288
289
     // Application main loop
290
     while (true)
291
     {
292
         // Feed inputs to dear imgui, start new frame
293
         ImGui_ImplDX11_NewFrame();
294
         ImGui_ImplWin32_NewFrame();
295
         ImGui::NewFrame();
296
297
         // Any application code here
298
         ImGui::Text("Hello, world!");
299
300
         // Render dear imgui into screen
301
         ImGui::Render();
302
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
303
         g_pSwapChain->Present(1, 0);
304
     }
305
306
     // Shutdown
307
     ImGui_ImplDX11_Shutdown();
308
     ImGui_ImplWin32_Shutdown();
309
     ImGui::DestroyContext();
310
311
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
312
313
     // Application init: create a dear imgui context, setup some options, load fonts
314
     ImGui::CreateContext();
315
     ImGuiIO& io = ImGui::GetIO();
316
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
317
     // TODO: Fill optional fields of the io structure later.
318
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
319
320
     // Build and load the texture atlas into a texture
321
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
322
     int width, height;
323
     unsigned char* pixels = nullptr;
324
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
325
326
     // At this point you've got the texture data and you need to upload that to your graphic system:
327
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
328
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
329
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
330
     io.Fonts->SetTexID((void*)texture);
331
332
     // Application main loop
333
     while (true)
334
     {
335
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
336
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
337
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
338
        io.DisplaySize.x = 1920.0f;             // set the current display width
339
        io.DisplaySize.y = 1280.0f;             // set the current display height here
340
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
341
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
342
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
343
344
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
345
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
346
        ImGui::NewFrame();
347
348
        // Most of your application code here
349
        ImGui::Text("Hello, world!");
350
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
351
        MyGameRender(); // may use any Dear ImGui functions as well!
352
353
        // Render dear imgui, swap buffers
354
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
355
        ImGui::EndFrame();
356
        ImGui::Render();
357
        ImDrawData* draw_data = ImGui::GetDrawData();
358
        MyImGuiRenderFunction(draw_data);
359
        SwapBuffers();
360
     }
361
362
     // Shutdown
363
     ImGui::DestroyContext();
364
365
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
366
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
367
 Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
368
369
370
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
371
 ---------------------------------------------
372
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
373
374
    void MyImGuiRenderFunction(ImDrawData* draw_data)
375
    {
376
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
377
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
378
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
379
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
380
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
381
       ImVec2 clip_off = draw_data->DisplayPos;
382
       for (int n = 0; n < draw_data->CmdListsCount; n++)
383
       {
384
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
385
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
386
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
387
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
388
          {
389
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
390
             if (pcmd->UserCallback)
391
             {
392
                 pcmd->UserCallback(cmd_list, pcmd);
393
             }
394
             else
395
             {
396
                 // Project scissor/clipping rectangles into framebuffer space
397
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
398
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
399
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
400
                     continue;
401
402
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
403
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
404
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
405
                 // - Clipping coordinates are provided in imgui coordinates space:
406
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
407
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
408
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
409
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
410
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
411
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
412
413
                 // The texture for the draw call is specified by pcmd->GetTexID().
414
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
415
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
416
417
                 // Render 'pcmd->ElemCount/3' indexed triangles.
418
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
419
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
420
             }
421
          }
422
       }
423
    }
424
425
426
 API BREAKING CHANGES
427
 ====================
428
429
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
430
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
431
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
432
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
433
434
(Docking/Viewport Branch)
435
 - 2024/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
436
                          - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
437
                            you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
438
                          - likewise io.MousePos and GetMousePos() will use OS coordinates.
439
                            If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
440
441
 - 2024/07/15 (1.91.0) - renamed ImGuiSelectableFlags_DontClosePopups to ImGuiSelectableFlags_NoAutoClosePopups. (#1379, #1468, #2200, #4936, #5216, #7302, #7573)
442
                         (internals: also renamed ImGuiItemFlags_SelectableDontClosePopup into ImGuiItemFlags_AutoClosePopups with inverted behaviors)
443
 - 2024/07/15 (1.91.0) - obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag(ImGuiItemFlags_ButtonRepeat, ...)/PopItemFlag().
444
 - 2024/07/02 (1.91.0) - commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456)
445
                       - commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456)
446
                            - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc.
447
 - 2024/07/02 (1.91.0) - IO, IME: renamed platform IME hook and added explicit context for consistency and future-proofness.
448
                            - old: io.SetPlatformImeDataFn(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
449
                            - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
450
 - 2024/06/21 (1.90.9) - BeginChild: added ImGuiChildFlags_NavFlattened as a replacement for the window flag ImGuiWindowFlags_NavFlattened: the feature only ever made sense for BeginChild() anyhow.
451
                            - old: BeginChild("Name", size, 0, ImGuiWindowFlags_NavFlattened);
452
                            - new: BeginChild("Name", size, ImGuiChildFlags_NavFlattened, 0);
453
 - 2024/06/21 (1.90.9) - io: ClearInputKeys() (first exposed in 1.89.8) doesn't clear mouse data, newly added ClearInputMouse() does.
454
 - 2024/06/20 (1.90.9) - renamed ImGuiDragDropFlags_SourceAutoExpirePayload to ImGuiDragDropFlags_PayloadAutoExpire.
455
 - 2024/06/18 (1.90.9) - style: renamed ImGuiCol_TabActive -> ImGuiCol_TabSelected, ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed, ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected.
456
 - 2024/06/10 (1.90.9) - removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages).
457
 - 2024/06/06 (1.90.8) - reordered ImGuiInputTextFlags values. This should not be breaking unless you are using generated headers that have values not matching the main library.
458
 - 2024/06/06 (1.90.8) - removed 'ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft', was mostly unused and misleading.
459
 - 2024/05/27 (1.90.7) - commented out obsolete symbols marked obsolete in 1.88 (May 2022):
460
                            - old: CaptureKeyboardFromApp(bool)
461
                            - new: SetNextFrameWantCaptureKeyboard(bool)
462
                            - old: CaptureMouseFromApp(bool)
463
                            - new: SetNextFrameWantCaptureMouse(bool)
464
 - 2024/05/22 (1.90.7) - inputs (internals): renamed ImGuiKeyOwner_None to ImGuiKeyOwner_NoOwner, to make use more explicit and reduce confusion with the default it is a non-zero value and cannot be the default value (never made public, but disclosing as I expect a few users caught on owner-aware inputs).
465
                       - inputs (internals): renamed ImGuiInputFlags_RouteGlobalLow -> ImGuiInputFlags_RouteGlobal, ImGuiInputFlags_RouteGlobal -> ImGuiInputFlags_RouteGlobalOverFocused, ImGuiInputFlags_RouteGlobalHigh -> ImGuiInputFlags_RouteGlobalHighest.
466
                       - inputs (internals): Shortcut(), SetShortcutRouting(): swapped last two parameters order in function signatures:
467
                            - old: Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id = 0, ImGuiInputFlags flags = 0);
468
                            - new: Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0, ImGuiID owner_id = 0);
469
                       - inputs (internals): owner-aware versions of IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(): swapped last two parameters order in function signatures.
470
                            - old: IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags = 0);
471
                            - new: IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0);
472
                            - old: IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags = 0);
473
                            - new: IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id = 0);
474
                         for various reasons those changes makes sense. They are being made because making some of those API public.
475
                         only past users of imgui_internal.h with the extra parameters will be affected. Added asserts for valid flags in various functions to detect _some_ misuses, BUT NOT ALL.
476
 - 2024/05/21 (1.90.7) - docking: changed signature of DockSpaceOverViewport() to add explicit dockspace id if desired. pass 0 to use old behavior. (#7611)
477
                           - old: DockSpaceOverViewport(const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...);
478
                           - new: DockSpaceOverViewport(ImGuiID dockspace_id = 0, const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...);
479
 - 2024/05/16 (1.90.7) - inputs: on macOS X, Cmd and Ctrl keys are now automatically swapped by io.AddKeyEvent() as this naturally align with how macOS X uses those keys.
480
                           - it shouldn't really affect you unless you had custom shortcut swapping in place for macOS X apps.
481
                           - removed ImGuiMod_Shortcut which was previously dynamically remapping to Ctrl or Cmd/Super. It is now unnecessary to specific cross-platform idiomatic shortcuts. (#2343, #4084, #5923, #456)
482
 - 2024/05/14 (1.90.7) - backends: SDL_Renderer2 and SDL_Renderer3 backend now take a SDL_Renderer* in their RenderDrawData() functions.
483
 - 2024/04/18 (1.90.6) - TreeNode: Fixed a layout inconsistency when using an empty/hidden label followed by a SameLine() call. (#7505, #282)
484
                           - old: TreeNode("##Hidden"); SameLine(); Text("Hello");     // <-- This was actually incorrect! BUT appeared to look ok with the default style where ItemSpacing.x == FramePadding.x * 2 (it didn't look aligned otherwise).
485
                           - new: TreeNode("##Hidden"); SameLine(0, 0); Text("Hello"); // <-- This is correct for all styles values.
486
                         with the fix, IF you were successfully using TreeNode("")+SameLine(); you will now have extra spacing between your TreeNode and the following item.
487
                         You'll need to change the SameLine() call to SameLine(0,0) to remove this extraneous spacing. This seemed like the more sensible fix that's not making things less consistent.
488
                         (Note: when using this idiom you are likely to also use ImGuiTreeNodeFlags_SpanAvailWidth).
489
 - 2024/03/18 (1.90.5) - merged the radius_x/radius_y parameters in ImDrawList::AddEllipse(), AddEllipseFilled() and PathEllipticalArcTo() into a single ImVec2 parameter. Exceptionally, because those functions were added in 1.90, we are not adding inline redirection functions. The transition is easy and should affect few users. (#2743, #7417)
490
 - 2024/03/08 (1.90.5) - inputs: more formally obsoleted GetKeyIndex() when IMGUI_DISABLE_OBSOLETE_FUNCTIONS is set. It has been unnecessary and a no-op since 1.87 (it returns the same value as passed when used with a 1.87+ backend using io.AddKeyEvent() function). (#4921)
491
                           - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
492
 - 2024/01/15 (1.90.2) - commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
493
 - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter.
494
 - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges.
495
 - 2023/11/05 (1.90.1) - imgui_freetype: commented out ImGuiFreeType::BuildFontAtlas() obsoleted in 1.81. prefer using #define IMGUI_ENABLE_FREETYPE or see commented code for manual calls.
496
 - 2023/11/05 (1.90.1) - internals,columns: commented out legacy ImGuiColumnsFlags_XXX symbols redirecting to ImGuiOldColumnsFlags_XXX, obsoleted from imgui_internal.h in 1.80.
497
 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
498
 - 2023/11/07 (1.90.0) - removed BeginChildFrame()/EndChildFrame() in favor of using BeginChild() with the ImGuiChildFlags_FrameStyle flag. kept inline redirection function (will obsolete).
499
                         those functions were merely PushStyle/PopStyle helpers, the removal isn't so much motivated by needing to add the feature in BeginChild(), but by the necessity to avoid BeginChildFrame() signature mismatching BeginChild() signature and features.
500
 - 2023/11/02 (1.90.0) - BeginChild: upgraded 'bool border = true' parameter to 'ImGuiChildFlags flags' type, added ImGuiChildFlags_Border equivalent. As with our prior "bool-to-flags" API updates, the ImGuiChildFlags_Border value is guaranteed to be == true forever to ensure a smoother transition, meaning all existing calls will still work.
501
                           - old: BeginChild("Name", size, true)
502
                           - new: BeginChild("Name", size, ImGuiChildFlags_Border)
503
                           - old: BeginChild("Name", size, false)
504
                           - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
505
 - 2023/11/02 (1.90.0) - BeginChild: added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense for BeginChild() anyhow.
506
                           - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
507
                           - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
508
 - 2023/09/27 (1.90.0) - io: removed io.MetricsActiveAllocations introduced in 1.63. Same as 'g.DebugMemAllocCount - g.DebugMemFreeCount' (still displayed in Metrics, unlikely to be accessed by end-user).
509
 - 2023/09/26 (1.90.0) - debug tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"), as earlier name was misleading. Kept inline redirection function. (#4631)
510
 - 2023/09/15 (1.90.0) - ListBox, Combo: changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis. kept inline redirection function (will obsolete).
511
                           - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
512
                           - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
513
                           - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
514
                           - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
515
 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
516
                           - GetWindowContentRegionWidth()  -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
517
                           - ImDrawCornerFlags_XXX          -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
518
                       - commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for AddRect()/AddRectFilled()/PathRect()/AddImageRounded() -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details
519
 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
520
 - 2023/07/12 (1.89.8) - ImDrawData: CmdLists now owned, changed from ImDrawList** to ImVector<ImDrawList*>. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. Instead use AddDrawList(). (#6406, #4879, #1878)
521
 - 2023/06/28 (1.89.7) - overlapping items: obsoleted 'SetItemAllowOverlap()' (called after item) in favor of calling 'SetNextItemAllowOverlap()' (called before item). 'SetItemAllowOverlap()' didn't and couldn't work reliably since 1.89 (2022-11-15).
522
 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
523
 - 2023/06/28 (1.89.7) - overlapping items: IsItemHovered() now by default return false when querying an item using AllowOverlap mode which is being overlapped. Use ImGuiHoveredFlags_AllowWhenOverlappedByItem to revert to old behavior.
524
 - 2023/06/28 (1.89.7) - overlapping items: Selectable and TreeNode don't allow overlap when active so overlapping widgets won't appear as hovered. While this fixes a common small visual issue, it also means that calling IsItemHovered() after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610)
525
 - 2023/06/20 (1.89.7) - moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only tweaked once during app initialization, we are exceptionally accepting the breakage.
526
 - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3.
527
 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
528
                           - ListBoxHeader()  -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
529
                           - ListBoxFooter()  -> use EndListBox()
530
 - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin().
531
 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
532
 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
533
                           - ImGuiSliderFlags_ClampOnInput        -> use ImGuiSliderFlags_AlwaysClamp
534
                           - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
535
                           - ImDrawList::AddBezierCurve()         -> use ImDrawList::AddBezierCubic()
536
                           - ImDrawList::PathBezierCurveTo()      -> use ImDrawList::PathBezierCubicCurveTo()
537
 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
538
 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
539
 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
540
                         Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
541
                         it has been frequently requested by people to use our own. We had an opt-in define which was
542
                         previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
543
                           - OK:     #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
544
                           - Error:  #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
545
 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
546
 - 2022/10/26 (1.89)   - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
547
 - 2022/10/12 (1.89)   - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
548
 - 2022/09/26 (1.89)   - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
549
                           - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
550
                           - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
551
                           - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
552
                           - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
553
                         the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
554
                         the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
555
                         exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
556
 - 2022/09/20 (1.89)   - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
557
                         this will require uses of legacy backend-dependent indices to be casted, e.g.
558
                            - with imgui_impl_glfw:  IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
559
                            - with imgui_impl_win32: IsKeyPressed('A')        -> IsKeyPressed((ImGuiKey)'A')
560
                            - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
561
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
562
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
563
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
564
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
565
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
566
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
567
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
568
                         - previously this would make the window content size ~200x200:
569
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
570
                         - instead, please submit an item:
571
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
572
                         - alternative:
573
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
574
                         - content size is now only extended when submitting an item!
575
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
576
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
577
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
578
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
579
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
580
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
581
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
582
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
583
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
584
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
585
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
586
                        - Official backends from 1.87+                  -> no issue.
587
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
588
                        - Custom backends not writing to io.NavInputs[] -> no issue.
589
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
590
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
591
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
592
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
593
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
594
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
595
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
596
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
597
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
598
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
599
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
600
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
601
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
602
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
603
                       read https://github.com/ocornut/imgui/issues/4921 for details.
604
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unnecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
605
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
606
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
607
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
608
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
609
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
610
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
611
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
612
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
613
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
614
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
615
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
616
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
617
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
618
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
619
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
620
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
621
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
622
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
623
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
624
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
625
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
626
                        - if you are using official backends from the source tree: you have nothing to do.
627
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
628
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
629
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
630
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
631
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
632
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
633
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
634
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
635
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
636
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
637
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
638
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
639
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
640
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
641
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
642
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
643
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
644
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
645
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
646
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
647
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
648
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
649
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
650
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
651
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
652
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
653
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
654
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
655
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
656
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
657
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
658
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
659
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
660
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
661
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
662
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
663
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
664
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
665
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
666
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
667
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
668
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
669
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
670
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
671
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
672
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
673
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
674
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
675
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
676
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
677
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
678
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
679
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
680
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
681
                       - if you omitted the 'power' parameter (likely!), you are not affected.
682
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
683
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
684
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
685
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
686
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
687
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
688
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
689
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
690
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
691
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
692
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
693
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
694
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
695
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
696
                       - ShowTestWindow()                    -> use ShowDemoWindow()
697
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
698
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
699
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
700
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
701
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
702
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
703
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
704
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
705
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
706
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
707
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
708
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
709
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
710
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
711
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
712
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
713
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
714
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
715
                       - ImFont::Glyph                       -> use ImFontGlyph
716
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
717
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
718
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
719
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
720
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
721
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
722
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
723
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
724
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
725
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
726
                       Please reach out if you are affected.
727
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
728
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
729
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
730
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
731
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
732
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
733
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
734
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
735
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
736
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
737
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
738
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
739
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
740
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
741
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
742
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
743
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
744
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
745
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
746
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
747
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
748
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
749
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
750
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
751
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
752
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
753
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
754
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
755
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
756
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
757
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
758
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
759
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
760
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
761
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
762
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
763
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
764
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
765
                       consistent with other functions. Kept redirection functions (will obsolete).
766
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
767
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
768
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
769
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
770
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
771
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
772
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
773
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
774
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
775
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
776
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
777
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
778
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
779
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
780
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
781
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
782
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
783
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
784
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
785
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
786
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
787
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
788
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
789
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
790
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
791
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
792
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
793
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
794
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
795
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
796
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
797
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
798
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
799
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
800
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
801
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
802
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
803
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
804
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
805
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
806
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
807
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
808
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
809
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
810
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
811
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
812
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
813
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
814
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
815
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
816
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
817
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
818
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
819
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
820
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
821
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
822
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
823
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
824
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
825
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
826
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
827
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
828
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
829
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
830
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
831
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
832
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
833
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
834
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
835
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
836
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
837
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
838
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
839
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
840
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
841
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
842
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
843
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
844
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
845
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
846
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
847
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
848
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
849
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
850
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
851
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
852
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
853
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
854
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
855
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
856
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
857
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
858
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
859
                     - the signature of the io.RenderDrawListsFn handler has changed!
860
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
861
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
862
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
863
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
864
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
865
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
866
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
867
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
868
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
869
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
870
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
871
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
872
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
873
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
874
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
875
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
876
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
877
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
878
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
879
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
880
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
881
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
882
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
883
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
884
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
885
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
886
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
887
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
888
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
889
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
890
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
891
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
892
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
893
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
894
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
895
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
896
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
897
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
898
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
899
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
900
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
901
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
902
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
903
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
904
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
905
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
906
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
907
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
908
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
909
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
910
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
911
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
912
913
914
 FREQUENTLY ASKED QUESTIONS (FAQ)
915
 ================================
916
917
 Read all answers online:
918
   https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
919
 Read all answers locally (with a text editor or ideally a Markdown viewer):
920
   docs/FAQ.md
921
 Some answers are copied down here to facilitate searching in code.
922
923
 Q&A: Basics
924
 ===========
925
926
 Q: Where is the documentation?
927
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
928
    - Run the examples/ applications and explore them.
929
    - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
930
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
931
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
932
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
933
    - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
934
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
935
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
936
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
937
    - Your programming IDE is your friend, find the type or function declaration to find comments
938
      associated with it.
939
940
 Q: What is this library called?
941
 Q: Which version should I get?
942
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
943
 >> See https://www.dearimgui.com/faq for details.
944
945
 Q&A: Integration
946
 ================
947
948
 Q: How to get started?
949
 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
950
951
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
952
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
953
 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
954
955
 Q. How can I enable keyboard or gamepad controls?
956
 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
957
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
958
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
959
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
960
 >> See https://www.dearimgui.com/faq
961
962
 Q&A: Usage
963
 ----------
964
965
 Q: About the ID Stack system..
966
   - Why is my widget not reacting when I click on it?
967
   - How can I have widgets with an empty label?
968
   - How can I have multiple widgets with the same label?
969
   - How can I have multiple windows with the same label?
970
 Q: How can I display an image? What is ImTextureID, how does it work?
971
 Q: How can I use my own math types instead of ImVec2?
972
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
973
 Q: How can I display custom shapes? (using low-level ImDrawList API)
974
 >> See https://www.dearimgui.com/faq
975
976
 Q&A: Fonts, Text
977
 ================
978
979
 Q: How should I handle DPI in my application?
980
 Q: How can I load a different font than the default?
981
 Q: How can I easily use icons in my application?
982
 Q: How can I load multiple fonts?
983
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
984
 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/blob/master/docs/FONTS.md
985
986
 Q&A: Concerns
987
 =============
988
989
 Q: Who uses Dear ImGui?
990
 Q: Can you create elaborate/serious tools with Dear ImGui?
991
 Q: Can you reskin the look of Dear ImGui?
992
 Q: Why using C++ (as opposed to C)?
993
 >> See https://www.dearimgui.com/faq
994
995
 Q&A: Community
996
 ==============
997
998
 Q: How can I help?
999
 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
1000
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
1001
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
1002
      >>> See https://github.com/ocornut/imgui/wiki/Funding
1003
    - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
1004
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, and see how you want to help and can help!
1005
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
1006
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
1007
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
1008
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
1009
1010
*/
1011
1012
//-------------------------------------------------------------------------
1013
// [SECTION] INCLUDES
1014
//-------------------------------------------------------------------------
1015
1016
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
1017
#define _CRT_SECURE_NO_WARNINGS
1018
#endif
1019
1020
#ifndef IMGUI_DEFINE_MATH_OPERATORS
1021
#define IMGUI_DEFINE_MATH_OPERATORS
1022
#endif
1023
1024
#include "imgui.h"
1025
#ifndef IMGUI_DISABLE
1026
#include "imgui_internal.h"
1027
1028
// System includes
1029
#include <stdio.h>      // vsnprintf, sscanf, printf
1030
#include <stdint.h>     // intptr_t
1031
1032
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
1033
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
1034
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1035
#endif
1036
1037
// [Windows] OS specific includes (optional)
1038
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1039
#define IMGUI_DISABLE_WIN32_FUNCTIONS
1040
#endif
1041
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1042
#ifndef WIN32_LEAN_AND_MEAN
1043
#define WIN32_LEAN_AND_MEAN
1044
#endif
1045
#ifndef NOMINMAX
1046
#define NOMINMAX
1047
#endif
1048
#ifndef __MINGW32__
1049
#include <Windows.h>        // _wfopen, OpenClipboard
1050
#else
1051
#include <windows.h>
1052
#endif
1053
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP || WINAPI_FAMILY == WINAPI_FAMILY_GAMES)
1054
// The UWP and GDK Win32 API subsets don't support clipboard nor IME functions
1055
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
1056
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1057
#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
1058
#endif
1059
#endif
1060
1061
// [Apple] OS specific includes
1062
#if defined(__APPLE__)
1063
#include <TargetConditionals.h>
1064
#endif
1065
1066
// Visual Studio warnings
1067
#ifdef _MSC_VER
1068
#pragma warning (disable: 4127)             // condition expression is constant
1069
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1070
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
1071
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
1072
#endif
1073
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
1074
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1075
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1076
#endif
1077
1078
// Clang/GCC warnings with -Weverything
1079
#if defined(__clang__)
1080
#if __has_warning("-Wunknown-warning-option")
1081
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
1082
#endif
1083
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
1084
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
1085
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
1086
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
1087
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
1088
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
1089
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
1090
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
1091
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
1092
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
1093
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
1094
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
1095
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage"            // warning: 'xxx' is an unsafe pointer used for buffer access
1096
#elif defined(__GNUC__)
1097
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1098
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
1099
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
1100
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
1101
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
1102
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
1103
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1104
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
1105
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1106
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
1107
#endif
1108
1109
// Debug options
1110
125k
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Hold CTRL to display for all candidates. CTRL+Arrow to change last direction.
1111
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
1112
1113
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
1114
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
1115
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
1116
1117
static const float NAV_ACTIVATE_HIGHLIGHT_TIMER             = 0.10f;    // Time to highlight an item activated by a shortcut.
1118
1119
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1120
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1121
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
1122
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
1123
1124
// Tooltip offset
1125
static const ImVec2 TOOLTIP_DEFAULT_OFFSET = ImVec2(16, 10);            // Multiplied by g.Style.MouseCursorScale
1126
1127
// Docking
1128
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1129
1130
//-------------------------------------------------------------------------
1131
// [SECTION] FORWARD DECLARATIONS
1132
//-------------------------------------------------------------------------
1133
1134
static void             SetCurrentWindow(ImGuiWindow* window);
1135
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1136
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1137
1138
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1139
1140
// Settings
1141
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1142
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1143
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1144
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1145
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1146
1147
// Platform Dependents default implementation for IO functions
1148
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1149
static void             SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1150
static void             PlatformSetImeDataFn_DefaultImpl(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1151
static bool             PlatformOpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path);
1152
1153
namespace ImGui
1154
{
1155
// Item
1156
static void             ItemHandleShortcut(ImGuiID id);
1157
1158
// Navigation
1159
static void             NavUpdate();
1160
static void             NavUpdateWindowing();
1161
static void             NavUpdateWindowingOverlay();
1162
static void             NavUpdateCancelRequest();
1163
static void             NavUpdateCreateMoveRequest();
1164
static void             NavUpdateCreateTabbingRequest();
1165
static float            NavUpdatePageUpPageDown();
1166
static inline void      NavUpdateAnyRequestFlag();
1167
static void             NavUpdateCreateWrappingRequest();
1168
static void             NavEndFrame();
1169
static bool             NavScoreItem(ImGuiNavItemData* result);
1170
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1171
static void             NavProcessItem();
1172
static void             NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1173
static ImVec2           NavCalcPreferredRefPos();
1174
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1175
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1176
static void             NavRestoreLayer(ImGuiNavLayer layer);
1177
static int              FindWindowFocusIndex(ImGuiWindow* window);
1178
1179
// Error Checking and Debug Tools
1180
static void             ErrorCheckNewFrameSanityChecks();
1181
static void             ErrorCheckEndFrameSanityChecks();
1182
static void             UpdateDebugToolItemPicker();
1183
static void             UpdateDebugToolStackQueries();
1184
static void             UpdateDebugToolFlashStyleColor();
1185
1186
// Inputs
1187
static void             UpdateKeyboardInputs();
1188
static void             UpdateMouseInputs();
1189
static void             UpdateMouseWheel();
1190
static void             UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1191
1192
// Misc
1193
static void             UpdateSettings();
1194
static int              UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1195
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1196
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1197
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1198
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1199
static void             RenderDimmedBackgrounds();
1200
static void             SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect);
1201
1202
// Viewports
1203
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1204
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1205
static void             DestroyViewport(ImGuiViewportP* viewport);
1206
static void             UpdateViewportsNewFrame();
1207
static void             UpdateViewportsEndFrame();
1208
static void             WindowSelectViewport(ImGuiWindow* window);
1209
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1210
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1211
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1212
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1213
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1214
static int              FindPlatformMonitorForRect(const ImRect& r);
1215
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1216
1217
}
1218
1219
//-----------------------------------------------------------------------------
1220
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1221
//-----------------------------------------------------------------------------
1222
1223
// DLL users:
1224
// - Heaps and globals are not shared across DLL boundaries!
1225
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1226
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1227
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1228
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1229
1230
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1231
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1232
//   Change to a different context by calling ImGui::SetCurrentContext().
1233
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1234
//   If you want thread-safety to allow N threads to access N different contexts:
1235
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1236
//         struct ImGuiContext;
1237
//         extern thread_local ImGuiContext* MyImGuiTLS;
1238
//         #define GImGui MyImGuiTLS
1239
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1240
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1241
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1242
// - DLL users: read comments above.
1243
#ifndef GImGui
1244
ImGuiContext*   GImGui = NULL;
1245
#endif
1246
1247
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1248
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1249
// - DLL users: read comments above.
1250
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1251
1.20k
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1252
1.15k
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1253
#else
1254
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1255
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1256
#endif
1257
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1258
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1259
static void*                GImAllocatorUserData = NULL;
1260
1261
//-----------------------------------------------------------------------------
1262
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1263
//-----------------------------------------------------------------------------
1264
1265
ImGuiStyle::ImGuiStyle()
1266
1
{
1267
1
    Alpha                       = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1268
1
    DisabledAlpha               = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1269
1
    WindowPadding               = ImVec2(8,8);      // Padding within a window
1270
1
    WindowRounding              = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1271
1
    WindowBorderSize            = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1272
1
    WindowMinSize               = ImVec2(32,32);    // Minimum window size
1273
1
    WindowTitleAlign            = ImVec2(0.0f,0.5f);// Alignment for title bar text
1274
1
    WindowMenuButtonPosition    = ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1275
1
    ChildRounding               = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1276
1
    ChildBorderSize             = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1277
1
    PopupRounding               = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1278
1
    PopupBorderSize             = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1279
1
    FramePadding                = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1280
1
    FrameRounding               = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1281
1
    FrameBorderSize             = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1282
1
    ItemSpacing                 = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1283
1
    ItemInnerSpacing            = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1284
1
    CellPadding                 = ImVec2(4,2);      // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows.
1285
1
    TouchExtraPadding           = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1286
1
    IndentSpacing               = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1287
1
    ColumnsMinSpacing           = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1288
1
    ScrollbarSize               = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1289
1
    ScrollbarRounding           = 9.0f;             // Radius of grab corners rounding for scrollbar
1290
1
    GrabMinSize                 = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1291
1
    GrabRounding                = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1292
1
    LogSliderDeadzone           = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1293
1
    TabRounding                 = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1294
1
    TabBorderSize               = 0.0f;             // Thickness of border around tabs.
1295
1
    TabMinWidthForCloseButton   = 0.0f;             // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1296
1
    TabBarBorderSize            = 1.0f;             // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1297
1
    TableAngledHeadersAngle     = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1298
1
    TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell
1299
1
    ColorButtonPosition         = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1300
1
    ButtonTextAlign             = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1301
1
    SelectableTextAlign         = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1302
1
    SeparatorTextBorderSize     = 3.0f;             // Thickkness of border in SeparatorText()
1303
1
    SeparatorTextAlign          = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1304
1
    SeparatorTextPadding        = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1305
1
    DisplayWindowPadding        = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1306
1
    DisplaySafeAreaPadding      = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1307
1
    DockingSeparatorSize        = 2.0f;             // Thickness of resizing border between docked windows
1308
1
    MouseCursorScale            = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1309
1
    AntiAliasedLines            = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1310
1
    AntiAliasedLinesUseTex      = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1311
1
    AntiAliasedFill             = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1312
1
    CurveTessellationTol        = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1313
1
    CircleTessellationMaxError  = 0.30f;            // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1314
1315
    // Behaviors
1316
1
    HoverStationaryDelay        = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1317
1
    HoverDelayShort             = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1318
1
    HoverDelayNormal            = 0.40f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1319
1
    HoverFlagsForTooltipMouse   = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled;    // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1320
1
    HoverFlagsForTooltipNav     = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled;  // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1321
1322
    // Default theme
1323
1
    ImGui::StyleColorsDark(this);
1324
1
}
1325
1326
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1327
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1328
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1329
0
{
1330
0
    WindowPadding = ImTrunc(WindowPadding * scale_factor);
1331
0
    WindowRounding = ImTrunc(WindowRounding * scale_factor);
1332
0
    WindowMinSize = ImTrunc(WindowMinSize * scale_factor);
1333
0
    ChildRounding = ImTrunc(ChildRounding * scale_factor);
1334
0
    PopupRounding = ImTrunc(PopupRounding * scale_factor);
1335
0
    FramePadding = ImTrunc(FramePadding * scale_factor);
1336
0
    FrameRounding = ImTrunc(FrameRounding * scale_factor);
1337
0
    ItemSpacing = ImTrunc(ItemSpacing * scale_factor);
1338
0
    ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor);
1339
0
    CellPadding = ImTrunc(CellPadding * scale_factor);
1340
0
    TouchExtraPadding = ImTrunc(TouchExtraPadding * scale_factor);
1341
0
    IndentSpacing = ImTrunc(IndentSpacing * scale_factor);
1342
0
    ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor);
1343
0
    ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor);
1344
0
    ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor);
1345
0
    GrabMinSize = ImTrunc(GrabMinSize * scale_factor);
1346
0
    GrabRounding = ImTrunc(GrabRounding * scale_factor);
1347
0
    LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor);
1348
0
    TabRounding = ImTrunc(TabRounding * scale_factor);
1349
0
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1350
0
    SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor);
1351
0
    DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor);
1352
0
    DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor);
1353
0
    DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor);
1354
0
    MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor);
1355
0
}
1356
1357
ImGuiIO::ImGuiIO()
1358
1
{
1359
    // Most fields are initialized with zero
1360
1
    memset(this, 0, sizeof(*this));
1361
1
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1362
1363
    // Settings
1364
1
    ConfigFlags = ImGuiConfigFlags_None;
1365
1
    BackendFlags = ImGuiBackendFlags_None;
1366
1
    DisplaySize = ImVec2(-1.0f, -1.0f);
1367
1
    DeltaTime = 1.0f / 60.0f;
1368
1
    IniSavingRate = 5.0f;
1369
1
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1370
1
    LogFilename = "imgui_log.txt";
1371
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1372
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1373
        KeyMap[i] = -1;
1374
#endif
1375
1
    UserData = NULL;
1376
1377
1
    Fonts = NULL;
1378
1
    FontGlobalScale = 1.0f;
1379
1
    FontDefault = NULL;
1380
1
    FontAllowUserScaling = false;
1381
1
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1382
1383
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1384
1
    ConfigDockingNoSplit = false;
1385
1
    ConfigDockingWithShift = false;
1386
1
    ConfigDockingAlwaysTabBar = false;
1387
1
    ConfigDockingTransparentPayload = false;
1388
1389
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1390
1
    ConfigViewportsNoAutoMerge = false;
1391
1
    ConfigViewportsNoTaskBarIcon = false;
1392
1
    ConfigViewportsNoDecoration = true;
1393
1
    ConfigViewportsNoDefaultParent = false;
1394
1395
    // Miscellaneous options
1396
1
    MouseDrawCursor = false;
1397
#ifdef __APPLE__
1398
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1399
#else
1400
1
    ConfigMacOSXBehaviors = false;
1401
1
#endif
1402
1
    ConfigInputTrickleEventQueue = true;
1403
1
    ConfigInputTextCursorBlink = true;
1404
1
    ConfigInputTextEnterKeepActive = false;
1405
1
    ConfigDragClickToInputText = false;
1406
1
    ConfigWindowsResizeFromEdges = true;
1407
1
    ConfigWindowsMoveFromTitleBarOnly = false;
1408
1
    ConfigMemoryCompactTimer = 60.0f;
1409
1
    ConfigDebugBeginReturnValueOnce = false;
1410
1
    ConfigDebugBeginReturnValueLoop = false;
1411
1412
    // Inputs Behaviors
1413
1
    MouseDoubleClickTime = 0.30f;
1414
1
    MouseDoubleClickMaxDist = 6.0f;
1415
1
    MouseDragThreshold = 6.0f;
1416
1
    KeyRepeatDelay = 0.275f;
1417
1
    KeyRepeatRate = 0.050f;
1418
1419
    // Platform Functions
1420
    // Note: Initialize() will setup default clipboard/ime handlers.
1421
1
    BackendPlatformName = BackendRendererName = NULL;
1422
1
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1423
1
    PlatformOpenInShellUserData = NULL;
1424
1
    PlatformLocaleDecimalPoint = '.';
1425
1426
    // Input (NB: we already have memset zero the entire structure!)
1427
1
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1428
1
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1429
1
    MouseSource = ImGuiMouseSource_Mouse;
1430
6
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1431
155
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1432
1
    AppAcceptingEvents = true;
1433
1
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1434
1
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1435
1
}
1436
1437
// Pass in translated ASCII characters for text input.
1438
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1439
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1440
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1441
void ImGuiIO::AddInputCharacter(unsigned int c)
1442
6.50k
{
1443
6.50k
    IM_ASSERT(Ctx != NULL);
1444
6.50k
    ImGuiContext& g = *Ctx;
1445
6.50k
    if (c == 0 || !AppAcceptingEvents)
1446
1.14k
        return;
1447
1448
5.36k
    ImGuiInputEvent e;
1449
5.36k
    e.Type = ImGuiInputEventType_Text;
1450
5.36k
    e.Source = ImGuiInputSource_Keyboard;
1451
5.36k
    e.EventId = g.InputEventsNextEventId++;
1452
5.36k
    e.Text.Char = c;
1453
5.36k
    g.InputEventsQueue.push_back(e);
1454
5.36k
}
1455
1456
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1457
// we should save the high surrogate.
1458
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1459
2.04k
{
1460
2.04k
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1461
110
        return;
1462
1463
1.93k
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1464
658
    {
1465
658
        if (InputQueueSurrogate != 0)
1466
212
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1467
658
        InputQueueSurrogate = c;
1468
658
        return;
1469
658
    }
1470
1471
1.27k
    ImWchar cp = c;
1472
1.27k
    if (InputQueueSurrogate != 0)
1473
433
    {
1474
433
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1475
399
        {
1476
399
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1477
399
        }
1478
34
        else
1479
34
        {
1480
34
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1481
34
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1482
#else
1483
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1484
#endif
1485
34
        }
1486
1487
433
        InputQueueSurrogate = 0;
1488
433
    }
1489
1.27k
    AddInputCharacter((unsigned)cp);
1490
1.27k
}
1491
1492
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1493
46
{
1494
46
    if (!AppAcceptingEvents)
1495
0
        return;
1496
46
    while (*utf8_chars != 0)
1497
0
    {
1498
0
        unsigned int c = 0;
1499
0
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1500
0
        AddInputCharacter(c);
1501
0
    }
1502
46
}
1503
1504
// Clear all incoming events.
1505
void ImGuiIO::ClearEventsQueue()
1506
0
{
1507
0
    IM_ASSERT(Ctx != NULL);
1508
0
    ImGuiContext& g = *Ctx;
1509
0
    g.InputEventsQueue.clear();
1510
0
}
1511
1512
// Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1513
void ImGuiIO::ClearInputKeys()
1514
11.2k
{
1515
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1516
    memset(KeysDown, 0, sizeof(KeysDown));
1517
#endif
1518
1.74M
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1519
1.72M
    {
1520
1.72M
        if (ImGui::IsMouseKey((ImGuiKey)(n + ImGuiKey_KeysData_OFFSET)))
1521
78.6k
            continue;
1522
1.65M
        KeysData[n].Down             = false;
1523
1.65M
        KeysData[n].DownDuration     = -1.0f;
1524
1.65M
        KeysData[n].DownDurationPrev = -1.0f;
1525
1.65M
    }
1526
11.2k
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1527
11.2k
    KeyMods = ImGuiMod_None;
1528
11.2k
    InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters().
1529
11.2k
}
1530
1531
void ImGuiIO::ClearInputMouse()
1532
2.47k
{
1533
19.7k
    for (ImGuiKey key = ImGuiKey_Mouse_BEGIN; key < ImGuiKey_Mouse_END; key = (ImGuiKey)(key + 1))
1534
17.3k
    {
1535
17.3k
        ImGuiKeyData* key_data = &KeysData[key - ImGuiKey_KeysData_OFFSET];
1536
17.3k
        key_data->Down = false;
1537
17.3k
        key_data->DownDuration = -1.0f;
1538
17.3k
        key_data->DownDurationPrev = -1.0f;
1539
17.3k
    }
1540
2.47k
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1541
14.8k
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1542
12.3k
    {
1543
12.3k
        MouseDown[n] = false;
1544
12.3k
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1545
12.3k
    }
1546
2.47k
    MouseWheel = MouseWheelH = 0.0f;
1547
2.47k
}
1548
1549
// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1550
// Current frame character buffer is now also cleared by ClearInputKeys().
1551
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1552
void ImGuiIO::ClearInputCharacters()
1553
{
1554
    InputQueueCharacters.resize(0);
1555
}
1556
#endif
1557
1558
static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1559
26.9k
{
1560
26.9k
    ImGuiContext& g = *ctx;
1561
47.0k
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1562
30.6k
    {
1563
30.6k
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1564
30.6k
        if (e->Type != type)
1565
17.2k
            continue;
1566
13.4k
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1567
1.98k
            continue;
1568
11.5k
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1569
917
            continue;
1570
10.5k
        return e;
1571
11.5k
    }
1572
16.3k
    return NULL;
1573
26.9k
}
1574
1575
// Queue a new key down/up event.
1576
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1577
// - bool down:          Is the key down? use false to signify a key release.
1578
// - float analog_value: 0.0f..1.0f
1579
// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1580
// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1581
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1582
7.06k
{
1583
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1584
7.06k
    IM_ASSERT(Ctx != NULL);
1585
7.06k
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1586
0
        return;
1587
7.06k
    ImGuiContext& g = *Ctx;
1588
7.06k
    IM_ASSERT(ImGui::IsNamedKeyOrMod(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1589
7.06k
    IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1590
1591
    // MacOS: swap Cmd(Super) and Ctrl
1592
7.06k
    if (g.IO.ConfigMacOSXBehaviors)
1593
0
    {
1594
0
        if (key == ImGuiMod_Super)          { key = ImGuiMod_Ctrl; }
1595
0
        else if (key == ImGuiMod_Ctrl)      { key = ImGuiMod_Super; }
1596
0
        else if (key == ImGuiKey_LeftSuper) { key = ImGuiKey_LeftCtrl; }
1597
0
        else if (key == ImGuiKey_RightSuper){ key = ImGuiKey_RightCtrl; }
1598
0
        else if (key == ImGuiKey_LeftCtrl)  { key = ImGuiKey_LeftSuper; }
1599
0
        else if (key == ImGuiKey_RightCtrl) { key = ImGuiKey_RightSuper; }
1600
0
    }
1601
1602
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1603
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1604
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1605
    if (BackendUsingLegacyKeyArrays == -1)
1606
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1607
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1608
    BackendUsingLegacyKeyArrays = 0;
1609
#endif
1610
7.06k
    if (ImGui::IsGamepadKey(key))
1611
34
        BackendUsingLegacyNavInputArray = false;
1612
1613
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1614
7.06k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1615
7.06k
    const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1616
7.06k
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1617
7.06k
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1618
7.06k
    if (latest_key_down == down && latest_key_analog == analog_value)
1619
1.00k
        return;
1620
1621
    // Add event
1622
6.06k
    ImGuiInputEvent e;
1623
6.06k
    e.Type = ImGuiInputEventType_Key;
1624
6.06k
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1625
6.06k
    e.EventId = g.InputEventsNextEventId++;
1626
6.06k
    e.Key.Key = key;
1627
6.06k
    e.Key.Down = down;
1628
6.06k
    e.Key.AnalogValue = analog_value;
1629
6.06k
    g.InputEventsQueue.push_back(e);
1630
6.06k
}
1631
1632
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1633
1.23k
{
1634
1.23k
    if (!AppAcceptingEvents)
1635
0
        return;
1636
1.23k
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1637
1.23k
}
1638
1639
// [Optional] Call after AddKeyEvent().
1640
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1641
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1642
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1643
0
{
1644
0
    if (key == ImGuiKey_None)
1645
0
        return;
1646
0
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1647
0
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1648
0
    IM_UNUSED(native_keycode);  // Yet unused
1649
0
    IM_UNUSED(native_scancode); // Yet unused
1650
1651
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1652
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1653
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1654
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1655
        return;
1656
    KeyMap[legacy_key] = key;
1657
    KeyMap[key] = legacy_key;
1658
#else
1659
0
    IM_UNUSED(key);
1660
0
    IM_UNUSED(native_legacy_index);
1661
0
#endif
1662
0
}
1663
1664
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1665
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1666
0
{
1667
0
    AppAcceptingEvents = accepting_events;
1668
0
}
1669
1670
// Queue a mouse move event
1671
void ImGuiIO::AddMousePosEvent(float x, float y)
1672
4.70k
{
1673
4.70k
    IM_ASSERT(Ctx != NULL);
1674
4.70k
    ImGuiContext& g = *Ctx;
1675
4.70k
    if (!AppAcceptingEvents)
1676
0
        return;
1677
1678
    // Apply same flooring as UpdateMouseInputs()
1679
4.70k
    ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y);
1680
1681
    // Filter duplicate
1682
4.70k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1683
4.70k
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1684
4.70k
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1685
880
        return;
1686
1687
3.82k
    ImGuiInputEvent e;
1688
3.82k
    e.Type = ImGuiInputEventType_MousePos;
1689
3.82k
    e.Source = ImGuiInputSource_Mouse;
1690
3.82k
    e.EventId = g.InputEventsNextEventId++;
1691
3.82k
    e.MousePos.PosX = pos.x;
1692
3.82k
    e.MousePos.PosY = pos.y;
1693
3.82k
    e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1694
3.82k
    g.InputEventsQueue.push_back(e);
1695
3.82k
}
1696
1697
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1698
12.0k
{
1699
12.0k
    IM_ASSERT(Ctx != NULL);
1700
12.0k
    ImGuiContext& g = *Ctx;
1701
12.0k
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1702
12.0k
    if (!AppAcceptingEvents)
1703
0
        return;
1704
1705
    // On MacOS X: Convert Ctrl(Super)+Left click into Right-click: handle held button.
1706
12.0k
    if (ConfigMacOSXBehaviors && mouse_button == 0 && MouseCtrlLeftAsRightClick)
1707
0
    {
1708
        // Order of both statements matterns: this event will still release mouse button 1
1709
0
        mouse_button = 1;
1710
0
        if (!down)
1711
0
            MouseCtrlLeftAsRightClick = false;
1712
0
    }
1713
1714
    // Filter duplicate
1715
12.0k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1716
12.0k
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1717
12.0k
    if (latest_button_down == down)
1718
3.99k
        return;
1719
1720
    // On MacOS X: Convert Ctrl(Super)+Left click into Right-click.
1721
    // - Note that this is actual physical Ctrl which is ImGuiMod_Super for us.
1722
    // - At this point we want from !down to down, so this is handling the initial press.
1723
8.03k
    if (ConfigMacOSXBehaviors && mouse_button == 0 && down)
1724
0
    {
1725
0
        const ImGuiInputEvent* latest_super_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)ImGuiMod_Super);
1726
0
        if (latest_super_event ? latest_super_event->Key.Down : g.IO.KeySuper)
1727
0
        {
1728
0
            IMGUI_DEBUG_LOG_IO("[io] Super+Left Click aliased into Right Click\n");
1729
0
            MouseCtrlLeftAsRightClick = true;
1730
0
            AddMouseButtonEvent(1, true); // This is just quicker to write that passing through, as we need to filter duplicate again.
1731
0
            return;
1732
0
        }
1733
0
    }
1734
1735
8.03k
    ImGuiInputEvent e;
1736
8.03k
    e.Type = ImGuiInputEventType_MouseButton;
1737
8.03k
    e.Source = ImGuiInputSource_Mouse;
1738
8.03k
    e.EventId = g.InputEventsNextEventId++;
1739
8.03k
    e.MouseButton.Button = mouse_button;
1740
8.03k
    e.MouseButton.Down = down;
1741
8.03k
    e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1742
8.03k
    g.InputEventsQueue.push_back(e);
1743
8.03k
}
1744
1745
// Queue a mouse wheel event (some mouse/API may only have a Y component)
1746
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1747
2.26k
{
1748
2.26k
    IM_ASSERT(Ctx != NULL);
1749
2.26k
    ImGuiContext& g = *Ctx;
1750
1751
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1752
2.26k
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1753
118
        return;
1754
1755
2.15k
    ImGuiInputEvent e;
1756
2.15k
    e.Type = ImGuiInputEventType_MouseWheel;
1757
2.15k
    e.Source = ImGuiInputSource_Mouse;
1758
2.15k
    e.EventId = g.InputEventsNextEventId++;
1759
2.15k
    e.MouseWheel.WheelX = wheel_x;
1760
2.15k
    e.MouseWheel.WheelY = wheel_y;
1761
2.15k
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1762
2.15k
    g.InputEventsQueue.push_back(e);
1763
2.15k
}
1764
1765
// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1766
// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1767
void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1768
0
{
1769
0
    IM_ASSERT(Ctx != NULL);
1770
0
    ImGuiContext& g = *Ctx;
1771
0
    g.InputEventsNextMouseSource = source;
1772
0
}
1773
1774
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1775
0
{
1776
0
    IM_ASSERT(Ctx != NULL);
1777
0
    ImGuiContext& g = *Ctx;
1778
    //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1779
0
    if (!AppAcceptingEvents)
1780
0
        return;
1781
1782
    // Filter duplicate
1783
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1784
0
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1785
0
    if (latest_viewport_id == viewport_id)
1786
0
        return;
1787
1788
0
    ImGuiInputEvent e;
1789
0
    e.Type = ImGuiInputEventType_MouseViewport;
1790
0
    e.Source = ImGuiInputSource_Mouse;
1791
0
    e.MouseViewport.HoveredViewportID = viewport_id;
1792
0
    g.InputEventsQueue.push_back(e);
1793
0
}
1794
1795
void ImGuiIO::AddFocusEvent(bool focused)
1796
3.15k
{
1797
3.15k
    IM_ASSERT(Ctx != NULL);
1798
3.15k
    ImGuiContext& g = *Ctx;
1799
1800
    // Filter duplicate
1801
3.15k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1802
3.15k
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1803
3.15k
    if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1804
444
        return;
1805
1806
2.71k
    ImGuiInputEvent e;
1807
2.71k
    e.Type = ImGuiInputEventType_Focus;
1808
2.71k
    e.EventId = g.InputEventsNextEventId++;
1809
2.71k
    e.AppFocused.Focused = focused;
1810
2.71k
    g.InputEventsQueue.push_back(e);
1811
2.71k
}
1812
1813
//-----------------------------------------------------------------------------
1814
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1815
//-----------------------------------------------------------------------------
1816
1817
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1818
0
{
1819
0
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1820
0
    ImVec2 p_last = p1;
1821
0
    ImVec2 p_closest;
1822
0
    float p_closest_dist2 = FLT_MAX;
1823
0
    float t_step = 1.0f / (float)num_segments;
1824
0
    for (int i_step = 1; i_step <= num_segments; i_step++)
1825
0
    {
1826
0
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1827
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1828
0
        float dist2 = ImLengthSqr(p - p_line);
1829
0
        if (dist2 < p_closest_dist2)
1830
0
        {
1831
0
            p_closest = p_line;
1832
0
            p_closest_dist2 = dist2;
1833
0
        }
1834
0
        p_last = p_current;
1835
0
    }
1836
0
    return p_closest;
1837
0
}
1838
1839
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1840
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1841
0
{
1842
0
    float dx = x4 - x1;
1843
0
    float dy = y4 - y1;
1844
0
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1845
0
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1846
0
    d2 = (d2 >= 0) ? d2 : -d2;
1847
0
    d3 = (d3 >= 0) ? d3 : -d3;
1848
0
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1849
0
    {
1850
0
        ImVec2 p_current(x4, y4);
1851
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1852
0
        float dist2 = ImLengthSqr(p - p_line);
1853
0
        if (dist2 < p_closest_dist2)
1854
0
        {
1855
0
            p_closest = p_line;
1856
0
            p_closest_dist2 = dist2;
1857
0
        }
1858
0
        p_last = p_current;
1859
0
    }
1860
0
    else if (level < 10)
1861
0
    {
1862
0
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1863
0
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1864
0
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1865
0
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1866
0
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1867
0
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1868
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1869
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1870
0
    }
1871
0
}
1872
1873
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1874
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1875
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1876
0
{
1877
0
    IM_ASSERT(tess_tol > 0.0f);
1878
0
    ImVec2 p_last = p1;
1879
0
    ImVec2 p_closest;
1880
0
    float p_closest_dist2 = FLT_MAX;
1881
0
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1882
0
    return p_closest;
1883
0
}
1884
1885
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1886
0
{
1887
0
    ImVec2 ap = p - a;
1888
0
    ImVec2 ab_dir = b - a;
1889
0
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1890
0
    if (dot < 0.0f)
1891
0
        return a;
1892
0
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1893
0
    if (dot > ab_len_sqr)
1894
0
        return b;
1895
0
    return a + ab_dir * dot / ab_len_sqr;
1896
0
}
1897
1898
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1899
0
{
1900
0
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1901
0
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1902
0
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1903
0
    return ((b1 == b2) && (b2 == b3));
1904
0
}
1905
1906
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1907
0
{
1908
0
    ImVec2 v0 = b - a;
1909
0
    ImVec2 v1 = c - a;
1910
0
    ImVec2 v2 = p - a;
1911
0
    const float denom = v0.x * v1.y - v1.x * v0.y;
1912
0
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1913
0
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1914
0
    out_u = 1.0f - out_v - out_w;
1915
0
}
1916
1917
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1918
0
{
1919
0
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1920
0
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1921
0
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1922
0
    float dist2_ab = ImLengthSqr(p - proj_ab);
1923
0
    float dist2_bc = ImLengthSqr(p - proj_bc);
1924
0
    float dist2_ca = ImLengthSqr(p - proj_ca);
1925
0
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1926
0
    if (m == dist2_ab)
1927
0
        return proj_ab;
1928
0
    if (m == dist2_bc)
1929
0
        return proj_bc;
1930
0
    return proj_ca;
1931
0
}
1932
1933
//-----------------------------------------------------------------------------
1934
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1935
//-----------------------------------------------------------------------------
1936
1937
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1938
int ImStricmp(const char* str1, const char* str2)
1939
0
{
1940
0
    int d;
1941
0
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1942
0
    return d;
1943
0
}
1944
1945
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1946
0
{
1947
0
    int d = 0;
1948
0
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1949
0
    return d;
1950
0
}
1951
1952
void ImStrncpy(char* dst, const char* src, size_t count)
1953
90
{
1954
90
    if (count < 1)
1955
0
        return;
1956
90
    if (count > 1)
1957
90
        strncpy(dst, src, count - 1);
1958
90
    dst[count - 1] = 0;
1959
90
}
1960
1961
char* ImStrdup(const char* str)
1962
3
{
1963
3
    size_t len = strlen(str);
1964
3
    void* buf = IM_ALLOC(len + 1);
1965
3
    return (char*)memcpy(buf, (const void*)str, len + 1);
1966
3
}
1967
1968
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1969
0
{
1970
0
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1971
0
    size_t src_size = strlen(src) + 1;
1972
0
    if (dst_buf_size < src_size)
1973
0
    {
1974
0
        IM_FREE(dst);
1975
0
        dst = (char*)IM_ALLOC(src_size);
1976
0
        if (p_dst_size)
1977
0
            *p_dst_size = src_size;
1978
0
    }
1979
0
    return (char*)memcpy(dst, (const void*)src, src_size);
1980
0
}
1981
1982
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1983
0
{
1984
0
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1985
0
    return p;
1986
0
}
1987
1988
int ImStrlenW(const ImWchar* str)
1989
0
{
1990
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
1991
0
    int n = 0;
1992
0
    while (*str++) n++;
1993
0
    return n;
1994
0
}
1995
1996
// Find end-of-line. Return pointer will point to either first \n, either str_end.
1997
const char* ImStreolRange(const char* str, const char* str_end)
1998
0
{
1999
0
    const char* p = (const char*)memchr(str, '\n', str_end - str);
2000
0
    return p ? p : str_end;
2001
0
}
2002
2003
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
2004
0
{
2005
0
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
2006
0
        buf_mid_line--;
2007
0
    return buf_mid_line;
2008
0
}
2009
2010
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
2011
0
{
2012
0
    if (!needle_end)
2013
0
        needle_end = needle + strlen(needle);
2014
2015
0
    const char un0 = (char)ImToUpper(*needle);
2016
0
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
2017
0
    {
2018
0
        if (ImToUpper(*haystack) == un0)
2019
0
        {
2020
0
            const char* b = needle + 1;
2021
0
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
2022
0
                if (ImToUpper(*a) != ImToUpper(*b))
2023
0
                    break;
2024
0
            if (b == needle_end)
2025
0
                return haystack;
2026
0
        }
2027
0
        haystack++;
2028
0
    }
2029
0
    return NULL;
2030
0
}
2031
2032
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
2033
void ImStrTrimBlanks(char* buf)
2034
0
{
2035
0
    char* p = buf;
2036
0
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
2037
0
        p++;
2038
0
    char* p_start = p;
2039
0
    while (*p != 0)                         // Find end of string
2040
0
        p++;
2041
0
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
2042
0
        p--;
2043
0
    if (p_start != buf)                     // Copy memory if we had leading blanks
2044
0
        memmove(buf, p_start, p - p_start);
2045
0
    buf[p - p_start] = 0;                   // Zero terminate
2046
0
}
2047
2048
const char* ImStrSkipBlank(const char* str)
2049
0
{
2050
0
    while (str[0] == ' ' || str[0] == '\t')
2051
0
        str++;
2052
0
    return str;
2053
0
}
2054
2055
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
2056
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
2057
// B) When buf==NULL vsnprintf() will return the output size.
2058
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2059
2060
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
2061
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2062
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
2063
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
2064
#ifdef IMGUI_USE_STB_SPRINTF
2065
#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
2066
#define STB_SPRINTF_IMPLEMENTATION
2067
#endif
2068
#ifdef IMGUI_STB_SPRINTF_FILENAME
2069
#include IMGUI_STB_SPRINTF_FILENAME
2070
#else
2071
#include "stb_sprintf.h"
2072
#endif
2073
#endif // #ifdef IMGUI_USE_STB_SPRINTF
2074
2075
#if defined(_MSC_VER) && !defined(vsnprintf)
2076
#define vsnprintf _vsnprintf
2077
#endif
2078
2079
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
2080
1
{
2081
1
    va_list args;
2082
1
    va_start(args, fmt);
2083
#ifdef IMGUI_USE_STB_SPRINTF
2084
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2085
#else
2086
1
    int w = vsnprintf(buf, buf_size, fmt, args);
2087
1
#endif
2088
1
    va_end(args);
2089
1
    if (buf == NULL)
2090
0
        return w;
2091
1
    if (w == -1 || w >= (int)buf_size)
2092
0
        w = (int)buf_size - 1;
2093
1
    buf[w] = 0;
2094
1
    return w;
2095
1
}
2096
2097
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
2098
10.2k
{
2099
#ifdef IMGUI_USE_STB_SPRINTF
2100
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2101
#else
2102
10.2k
    int w = vsnprintf(buf, buf_size, fmt, args);
2103
10.2k
#endif
2104
10.2k
    if (buf == NULL)
2105
0
        return w;
2106
10.2k
    if (w == -1 || w >= (int)buf_size)
2107
0
        w = (int)buf_size - 1;
2108
10.2k
    buf[w] = 0;
2109
10.2k
    return w;
2110
10.2k
}
2111
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2112
2113
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
2114
10.2k
{
2115
10.2k
    va_list args;
2116
10.2k
    va_start(args, fmt);
2117
10.2k
    ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
2118
10.2k
    va_end(args);
2119
10.2k
}
2120
2121
// FIXME: Should rework API toward allowing multiple in-flight temp buffers (easier and safer for caller)
2122
// by making the caller acquire a temp buffer token, with either explicit or destructor release, e.g.
2123
//  ImGuiTempBufferToken token;
2124
//  ImFormatStringToTempBuffer(token, ...);
2125
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2126
10.2k
{
2127
10.2k
    ImGuiContext& g = *GImGui;
2128
10.2k
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2129
0
    {
2130
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2131
0
        if (buf == NULL)
2132
0
            buf = "(null)";
2133
0
        *out_buf = buf;
2134
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
2135
0
    }
2136
10.2k
    else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2137
0
    {
2138
0
        int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2139
0
        const char* buf = va_arg(args, const char*);
2140
0
        if (buf == NULL)
2141
0
        {
2142
0
            buf = "(null)";
2143
0
            buf_len = ImMin(buf_len, 6);
2144
0
        }
2145
0
        *out_buf = buf;
2146
0
        *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2147
0
    }
2148
10.2k
    else
2149
10.2k
    {
2150
10.2k
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
2151
10.2k
        *out_buf = g.TempBuffer.Data;
2152
10.2k
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2153
10.2k
    }
2154
10.2k
}
2155
2156
// CRC32 needs a 1KB lookup table (not cache friendly)
2157
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2158
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2159
static const ImU32 GCrc32LookupTable[256] =
2160
{
2161
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2162
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2163
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2164
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2165
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2166
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2167
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2168
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2169
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2170
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2171
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2172
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2173
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2174
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2175
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2176
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2177
};
2178
2179
// Known size hash
2180
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2181
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2182
ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2183
61.3k
{
2184
61.3k
    ImU32 crc = ~seed;
2185
61.3k
    const unsigned char* data = (const unsigned char*)data_p;
2186
61.3k
    const ImU32* crc32_lut = GCrc32LookupTable;
2187
306k
    while (data_size-- != 0)
2188
245k
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2189
61.3k
    return ~crc;
2190
61.3k
}
2191
2192
// Zero-terminated string hash, with support for ### to reset back to seed value
2193
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2194
// Because this syntax is rarely used we are optimizing for the common case.
2195
// - If we reach ### in the string we discard the hash so far and reset to the seed.
2196
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2197
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2198
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2199
353k
{
2200
353k
    seed = ~seed;
2201
353k
    ImU32 crc = seed;
2202
353k
    const unsigned char* data = (const unsigned char*)data_p;
2203
353k
    const ImU32* crc32_lut = GCrc32LookupTable;
2204
353k
    if (data_size != 0)
2205
0
    {
2206
0
        while (data_size-- != 0)
2207
0
        {
2208
0
            unsigned char c = *data++;
2209
0
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2210
0
                crc = seed;
2211
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2212
0
        }
2213
0
    }
2214
353k
    else
2215
353k
    {
2216
4.83M
        while (unsigned char c = *data++)
2217
4.48M
        {
2218
4.48M
            if (c == '#' && data[0] == '#' && data[1] == '#')
2219
58.4k
                crc = seed;
2220
4.48M
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2221
4.48M
        }
2222
353k
    }
2223
353k
    return ~crc;
2224
353k
}
2225
2226
//-----------------------------------------------------------------------------
2227
// [SECTION] MISC HELPERS/UTILITIES (File functions)
2228
//-----------------------------------------------------------------------------
2229
2230
// Default file functions
2231
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2232
2233
ImFileHandle ImFileOpen(const char* filename, const char* mode)
2234
0
{
2235
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2236
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2237
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2238
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2239
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2240
2241
    // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator.
2242
    // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314).
2243
    wchar_t local_temp_stack[FILENAME_MAX];
2244
    ImVector<wchar_t> local_temp_heap;
2245
    if (filename_wsize + mode_wsize > IM_ARRAYSIZE(local_temp_stack))
2246
        local_temp_heap.resize(filename_wsize + mode_wsize);
2247
    wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack;
2248
    wchar_t* mode_wbuf = filename_wbuf + filename_wsize;
2249
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize);
2250
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize);
2251
    return ::_wfopen(filename_wbuf, mode_wbuf);
2252
#else
2253
0
    return fopen(filename, mode);
2254
0
#endif
2255
0
}
2256
2257
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2258
0
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
2259
0
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2260
0
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
2261
0
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
2262
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2263
2264
// Helper: Load file content into memory
2265
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2266
// This can't really be used with "rt" because fseek size won't match read size.
2267
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2268
0
{
2269
0
    IM_ASSERT(filename && mode);
2270
0
    if (out_file_size)
2271
0
        *out_file_size = 0;
2272
2273
0
    ImFileHandle f;
2274
0
    if ((f = ImFileOpen(filename, mode)) == NULL)
2275
0
        return NULL;
2276
2277
0
    size_t file_size = (size_t)ImFileGetSize(f);
2278
0
    if (file_size == (size_t)-1)
2279
0
    {
2280
0
        ImFileClose(f);
2281
0
        return NULL;
2282
0
    }
2283
2284
0
    void* file_data = IM_ALLOC(file_size + padding_bytes);
2285
0
    if (file_data == NULL)
2286
0
    {
2287
0
        ImFileClose(f);
2288
0
        return NULL;
2289
0
    }
2290
0
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
2291
0
    {
2292
0
        ImFileClose(f);
2293
0
        IM_FREE(file_data);
2294
0
        return NULL;
2295
0
    }
2296
0
    if (padding_bytes > 0)
2297
0
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2298
2299
0
    ImFileClose(f);
2300
0
    if (out_file_size)
2301
0
        *out_file_size = file_size;
2302
2303
0
    return file_data;
2304
0
}
2305
2306
//-----------------------------------------------------------------------------
2307
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2308
//-----------------------------------------------------------------------------
2309
2310
IM_MSVC_RUNTIME_CHECKS_OFF
2311
2312
// Convert UTF-8 to 32-bit character, process single character input.
2313
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2314
// We handle UTF-8 decoding error by skipping forward.
2315
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2316
72.7k
{
2317
72.7k
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2318
72.7k
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2319
72.7k
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2320
72.7k
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2321
72.7k
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2322
72.7k
    int len = lengths[*(const unsigned char*)in_text >> 3];
2323
72.7k
    int wanted = len + (len ? 0 : 1);
2324
2325
72.7k
    if (in_text_end == NULL)
2326
0
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2327
2328
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2329
    // so it is fast even with excessive branching.
2330
72.7k
    unsigned char s[4];
2331
72.7k
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2332
72.7k
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2333
72.7k
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2334
72.7k
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2335
2336
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2337
72.7k
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2338
72.7k
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2339
72.7k
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2340
72.7k
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2341
72.7k
    *out_char >>= shiftc[len];
2342
2343
    // Accumulate the various error conditions.
2344
72.7k
    int e = 0;
2345
72.7k
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2346
72.7k
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2347
72.7k
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2348
72.7k
    e |= (s[1] & 0xc0) >> 2;
2349
72.7k
    e |= (s[2] & 0xc0) >> 4;
2350
72.7k
    e |= (s[3]       ) >> 6;
2351
72.7k
    e ^= 0x2a; // top two bits of each tail byte correct?
2352
72.7k
    e >>= shifte[len];
2353
2354
72.7k
    if (e)
2355
4.41k
    {
2356
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2357
        // One byte is consumed in case of invalid first byte of in_text.
2358
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2359
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2360
4.41k
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2361
4.41k
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2362
4.41k
    }
2363
2364
72.7k
    return wanted;
2365
72.7k
}
2366
2367
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2368
0
{
2369
0
    ImWchar* buf_out = buf;
2370
0
    ImWchar* buf_end = buf + buf_size;
2371
0
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2372
0
    {
2373
0
        unsigned int c;
2374
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2375
0
        *buf_out++ = (ImWchar)c;
2376
0
    }
2377
0
    *buf_out = 0;
2378
0
    if (in_text_remaining)
2379
0
        *in_text_remaining = in_text;
2380
0
    return (int)(buf_out - buf);
2381
0
}
2382
2383
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2384
0
{
2385
0
    int char_count = 0;
2386
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2387
0
    {
2388
0
        unsigned int c;
2389
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2390
0
        char_count++;
2391
0
    }
2392
0
    return char_count;
2393
0
}
2394
2395
// Based on stb_to_utf8() from github.com/nothings/stb/
2396
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2397
0
{
2398
0
    if (c < 0x80)
2399
0
    {
2400
0
        buf[0] = (char)c;
2401
0
        return 1;
2402
0
    }
2403
0
    if (c < 0x800)
2404
0
    {
2405
0
        if (buf_size < 2) return 0;
2406
0
        buf[0] = (char)(0xc0 + (c >> 6));
2407
0
        buf[1] = (char)(0x80 + (c & 0x3f));
2408
0
        return 2;
2409
0
    }
2410
0
    if (c < 0x10000)
2411
0
    {
2412
0
        if (buf_size < 3) return 0;
2413
0
        buf[0] = (char)(0xe0 + (c >> 12));
2414
0
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2415
0
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2416
0
        return 3;
2417
0
    }
2418
0
    if (c <= 0x10FFFF)
2419
0
    {
2420
0
        if (buf_size < 4) return 0;
2421
0
        buf[0] = (char)(0xf0 + (c >> 18));
2422
0
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2423
0
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2424
0
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2425
0
        return 4;
2426
0
    }
2427
    // Invalid code point, the max unicode is 0x10FFFF
2428
0
    return 0;
2429
0
}
2430
2431
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2432
0
{
2433
0
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2434
0
    out_buf[count] = 0;
2435
0
    return out_buf;
2436
0
}
2437
2438
// Not optimal but we very rarely use this function.
2439
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2440
0
{
2441
0
    unsigned int unused = 0;
2442
0
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2443
0
}
2444
2445
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2446
0
{
2447
0
    if (c < 0x80) return 1;
2448
0
    if (c < 0x800) return 2;
2449
0
    if (c < 0x10000) return 3;
2450
0
    if (c <= 0x10FFFF) return 4;
2451
0
    return 3;
2452
0
}
2453
2454
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2455
0
{
2456
0
    char* buf_p = out_buf;
2457
0
    const char* buf_end = out_buf + out_buf_size;
2458
0
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2459
0
    {
2460
0
        unsigned int c = (unsigned int)(*in_text++);
2461
0
        if (c < 0x80)
2462
0
            *buf_p++ = (char)c;
2463
0
        else
2464
0
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2465
0
    }
2466
0
    *buf_p = 0;
2467
0
    return (int)(buf_p - out_buf);
2468
0
}
2469
2470
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2471
0
{
2472
0
    int bytes_count = 0;
2473
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2474
0
    {
2475
0
        unsigned int c = (unsigned int)(*in_text++);
2476
0
        if (c < 0x80)
2477
0
            bytes_count++;
2478
0
        else
2479
0
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2480
0
    }
2481
0
    return bytes_count;
2482
0
}
2483
2484
const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2485
0
{
2486
0
    while (in_text_curr > in_text_start)
2487
0
    {
2488
0
        in_text_curr--;
2489
0
        if ((*in_text_curr & 0xC0) != 0x80)
2490
0
            return in_text_curr;
2491
0
    }
2492
0
    return in_text_start;
2493
0
}
2494
2495
int ImTextCountLines(const char* in_text, const char* in_text_end)
2496
0
{
2497
0
    if (in_text_end == NULL)
2498
0
        in_text_end = in_text + strlen(in_text); // FIXME-OPT: Not optimal approach, discourage use for now.
2499
0
    int count = 0;
2500
0
    while (in_text < in_text_end)
2501
0
    {
2502
0
        const char* line_end = (const char*)memchr(in_text, '\n', in_text_end - in_text);
2503
0
        in_text = line_end ? line_end + 1 : in_text_end;
2504
0
        count++;
2505
0
    }
2506
0
    return count;
2507
0
}
2508
2509
IM_MSVC_RUNTIME_CHECKS_RESTORE
2510
2511
//-----------------------------------------------------------------------------
2512
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2513
// Note: The Convert functions are early design which are not consistent with other API.
2514
//-----------------------------------------------------------------------------
2515
2516
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2517
0
{
2518
0
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2519
0
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2520
0
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2521
0
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2522
0
    return IM_COL32(r, g, b, 0xFF);
2523
0
}
2524
2525
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2526
181k
{
2527
181k
    float s = 1.0f / 255.0f;
2528
181k
    return ImVec4(
2529
181k
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2530
181k
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2531
181k
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2532
181k
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2533
181k
}
2534
2535
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2536
873k
{
2537
873k
    ImU32 out;
2538
873k
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2539
873k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2540
873k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2541
873k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2542
873k
    return out;
2543
873k
}
2544
2545
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2546
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2547
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2548
0
{
2549
0
    float K = 0.f;
2550
0
    if (g < b)
2551
0
    {
2552
0
        ImSwap(g, b);
2553
0
        K = -1.f;
2554
0
    }
2555
0
    if (r < g)
2556
0
    {
2557
0
        ImSwap(r, g);
2558
0
        K = -2.f / 6.f - K;
2559
0
    }
2560
2561
0
    const float chroma = r - (g < b ? g : b);
2562
0
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2563
0
    out_s = chroma / (r + 1e-20f);
2564
0
    out_v = r;
2565
0
}
2566
2567
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2568
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2569
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2570
0
{
2571
0
    if (s == 0.0f)
2572
0
    {
2573
        // gray
2574
0
        out_r = out_g = out_b = v;
2575
0
        return;
2576
0
    }
2577
2578
0
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2579
0
    int   i = (int)h;
2580
0
    float f = h - (float)i;
2581
0
    float p = v * (1.0f - s);
2582
0
    float q = v * (1.0f - s * f);
2583
0
    float t = v * (1.0f - s * (1.0f - f));
2584
2585
0
    switch (i)
2586
0
    {
2587
0
    case 0: out_r = v; out_g = t; out_b = p; break;
2588
0
    case 1: out_r = q; out_g = v; out_b = p; break;
2589
0
    case 2: out_r = p; out_g = v; out_b = t; break;
2590
0
    case 3: out_r = p; out_g = q; out_b = v; break;
2591
0
    case 4: out_r = t; out_g = p; out_b = v; break;
2592
0
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2593
0
    }
2594
0
}
2595
2596
//-----------------------------------------------------------------------------
2597
// [SECTION] ImGuiStorage
2598
// Helper: Key->value storage
2599
//-----------------------------------------------------------------------------
2600
2601
// std::lower_bound but without the bullshit
2602
ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key)
2603
127k
{
2604
127k
    ImGuiStoragePair* in_p = in_begin;
2605
381k
    for (size_t count = (size_t)(in_end - in_p); count > 0; )
2606
254k
    {
2607
254k
        size_t count2 = count >> 1;
2608
254k
        ImGuiStoragePair* mid = in_p + count2;
2609
254k
        if (mid->key < key)
2610
68.7k
        {
2611
68.7k
            in_p = ++mid;
2612
68.7k
            count -= count2 + 1;
2613
68.7k
        }
2614
185k
        else
2615
185k
        {
2616
185k
            count = count2;
2617
185k
        }
2618
254k
    }
2619
127k
    return in_p;
2620
127k
}
2621
2622
IM_MSVC_RUNTIME_CHECKS_OFF
2623
static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2624
0
{
2625
    // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2626
0
    ImGuiID lhs_v = ((const ImGuiStoragePair*)lhs)->key;
2627
0
    ImGuiID rhs_v = ((const ImGuiStoragePair*)rhs)->key;
2628
0
    return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0);
2629
0
}
2630
2631
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2632
void ImGuiStorage::BuildSortByKey()
2633
0
{
2634
0
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), PairComparerByID);
2635
0
}
2636
IM_MSVC_RUNTIME_CHECKS_RESTORE
2637
2638
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2639
0
{
2640
0
    ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2641
0
    if (it == Data.end() || it->key != key)
2642
0
        return default_val;
2643
0
    return it->val_i;
2644
0
}
2645
2646
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2647
0
{
2648
0
    return GetInt(key, default_val ? 1 : 0) != 0;
2649
0
}
2650
2651
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2652
0
{
2653
0
    ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2654
0
    if (it == Data.end() || it->key != key)
2655
0
        return default_val;
2656
0
    return it->val_f;
2657
0
}
2658
2659
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2660
127k
{
2661
127k
    ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2662
127k
    if (it == Data.end() || it->key != key)
2663
3
        return NULL;
2664
127k
    return it->val_p;
2665
127k
}
2666
2667
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2668
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2669
0
{
2670
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2671
0
    if (it == Data.end() || it->key != key)
2672
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2673
0
    return &it->val_i;
2674
0
}
2675
2676
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2677
0
{
2678
0
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2679
0
}
2680
2681
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2682
0
{
2683
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2684
0
    if (it == Data.end() || it->key != key)
2685
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2686
0
    return &it->val_f;
2687
0
}
2688
2689
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2690
0
{
2691
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2692
0
    if (it == Data.end() || it->key != key)
2693
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2694
0
    return &it->val_p;
2695
0
}
2696
2697
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2698
void ImGuiStorage::SetInt(ImGuiID key, int val)
2699
0
{
2700
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2701
0
    if (it == Data.end() || it->key != key)
2702
0
        Data.insert(it, ImGuiStoragePair(key, val));
2703
0
    else
2704
0
        it->val_i = val;
2705
0
}
2706
2707
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2708
0
{
2709
0
    SetInt(key, val ? 1 : 0);
2710
0
}
2711
2712
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2713
0
{
2714
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2715
0
    if (it == Data.end() || it->key != key)
2716
0
        Data.insert(it, ImGuiStoragePair(key, val));
2717
0
    else
2718
0
        it->val_f = val;
2719
0
}
2720
2721
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2722
3
{
2723
3
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2724
3
    if (it == Data.end() || it->key != key)
2725
3
        Data.insert(it, ImGuiStoragePair(key, val));
2726
0
    else
2727
0
        it->val_p = val;
2728
3
}
2729
2730
void ImGuiStorage::SetAllInt(int v)
2731
0
{
2732
0
    for (int i = 0; i < Data.Size; i++)
2733
0
        Data[i].val_i = v;
2734
0
}
2735
2736
//-----------------------------------------------------------------------------
2737
// [SECTION] ImGuiTextFilter
2738
//-----------------------------------------------------------------------------
2739
2740
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2741
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2742
0
{
2743
0
    InputBuf[0] = 0;
2744
0
    CountGrep = 0;
2745
0
    if (default_filter)
2746
0
    {
2747
0
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2748
0
        Build();
2749
0
    }
2750
0
}
2751
2752
bool ImGuiTextFilter::Draw(const char* label, float width)
2753
0
{
2754
0
    if (width != 0.0f)
2755
0
        ImGui::SetNextItemWidth(width);
2756
0
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2757
0
    if (value_changed)
2758
0
        Build();
2759
0
    return value_changed;
2760
0
}
2761
2762
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2763
0
{
2764
0
    out->resize(0);
2765
0
    const char* wb = b;
2766
0
    const char* we = wb;
2767
0
    while (we < e)
2768
0
    {
2769
0
        if (*we == separator)
2770
0
        {
2771
0
            out->push_back(ImGuiTextRange(wb, we));
2772
0
            wb = we + 1;
2773
0
        }
2774
0
        we++;
2775
0
    }
2776
0
    if (wb != we)
2777
0
        out->push_back(ImGuiTextRange(wb, we));
2778
0
}
2779
2780
void ImGuiTextFilter::Build()
2781
0
{
2782
0
    Filters.resize(0);
2783
0
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2784
0
    input_range.split(',', &Filters);
2785
2786
0
    CountGrep = 0;
2787
0
    for (ImGuiTextRange& f : Filters)
2788
0
    {
2789
0
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2790
0
            f.b++;
2791
0
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2792
0
            f.e--;
2793
0
        if (f.empty())
2794
0
            continue;
2795
0
        if (f.b[0] != '-')
2796
0
            CountGrep += 1;
2797
0
    }
2798
0
}
2799
2800
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2801
0
{
2802
0
    if (Filters.empty())
2803
0
        return true;
2804
2805
0
    if (text == NULL)
2806
0
        text = "";
2807
2808
0
    for (const ImGuiTextRange& f : Filters)
2809
0
    {
2810
0
        if (f.empty())
2811
0
            continue;
2812
0
        if (f.b[0] == '-')
2813
0
        {
2814
            // Subtract
2815
0
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2816
0
                return false;
2817
0
        }
2818
0
        else
2819
0
        {
2820
            // Grep
2821
0
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2822
0
                return true;
2823
0
        }
2824
0
    }
2825
2826
    // Implicit * grep
2827
0
    if (CountGrep == 0)
2828
0
        return true;
2829
2830
0
    return false;
2831
0
}
2832
2833
//-----------------------------------------------------------------------------
2834
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2835
//-----------------------------------------------------------------------------
2836
2837
// On some platform vsnprintf() takes va_list by reference and modifies it.
2838
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2839
#ifndef va_copy
2840
#if defined(__GNUC__) || defined(__clang__)
2841
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2842
#else
2843
#define va_copy(dest, src) (dest = src)
2844
#endif
2845
#endif
2846
2847
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2848
2849
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2850
0
{
2851
0
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2852
2853
    // Add zero-terminator the first time
2854
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2855
0
    const int needed_sz = write_off + len;
2856
0
    if (write_off + len >= Buf.Capacity)
2857
0
    {
2858
0
        int new_capacity = Buf.Capacity * 2;
2859
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2860
0
    }
2861
2862
0
    Buf.resize(needed_sz);
2863
0
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2864
0
    Buf[write_off - 1 + len] = 0;
2865
0
}
2866
2867
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2868
0
{
2869
0
    va_list args;
2870
0
    va_start(args, fmt);
2871
0
    appendfv(fmt, args);
2872
0
    va_end(args);
2873
0
}
2874
2875
// Helper: Text buffer for logging/accumulating text
2876
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2877
0
{
2878
0
    va_list args_copy;
2879
0
    va_copy(args_copy, args);
2880
2881
0
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2882
0
    if (len <= 0)
2883
0
    {
2884
0
        va_end(args_copy);
2885
0
        return;
2886
0
    }
2887
2888
    // Add zero-terminator the first time
2889
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2890
0
    const int needed_sz = write_off + len;
2891
0
    if (write_off + len >= Buf.Capacity)
2892
0
    {
2893
0
        int new_capacity = Buf.Capacity * 2;
2894
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2895
0
    }
2896
2897
0
    Buf.resize(needed_sz);
2898
0
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2899
0
    va_end(args_copy);
2900
0
}
2901
2902
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2903
0
{
2904
0
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2905
0
    if (old_size == new_size)
2906
0
        return;
2907
0
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2908
0
        LineOffsets.push_back(EndOffset);
2909
0
    const char* base_end = base + new_size;
2910
0
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2911
0
        if (++p < base_end) // Don't push a trailing offset on last \n
2912
0
            LineOffsets.push_back((int)(intptr_t)(p - base));
2913
0
    EndOffset = ImMax(EndOffset, new_size);
2914
0
}
2915
2916
//-----------------------------------------------------------------------------
2917
// [SECTION] ImGuiListClipper
2918
//-----------------------------------------------------------------------------
2919
2920
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2921
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2922
static bool GetSkipItemForListClipping()
2923
0
{
2924
0
    ImGuiContext& g = *GImGui;
2925
0
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2926
0
}
2927
2928
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2929
0
{
2930
0
    if (ranges.Size - offset <= 1)
2931
0
        return;
2932
2933
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2934
0
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2935
0
        for (int i = offset; i < sort_end + offset; ++i)
2936
0
            if (ranges[i].Min > ranges[i + 1].Min)
2937
0
                ImSwap(ranges[i], ranges[i + 1]);
2938
2939
    // Now fuse ranges together as much as possible.
2940
0
    for (int i = 1 + offset; i < ranges.Size; i++)
2941
0
    {
2942
0
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2943
0
        if (ranges[i - 1].Max < ranges[i].Min)
2944
0
            continue;
2945
0
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2946
0
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2947
0
        ranges.erase(ranges.Data + i);
2948
0
        i--;
2949
0
    }
2950
0
}
2951
2952
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2953
0
{
2954
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2955
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2956
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2957
0
    ImGuiContext& g = *GImGui;
2958
0
    ImGuiWindow* window = g.CurrentWindow;
2959
0
    float off_y = pos_y - window->DC.CursorPos.y;
2960
0
    window->DC.CursorPos.y = pos_y;
2961
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2962
0
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2963
0
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2964
0
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2965
0
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2966
0
    if (ImGuiTable* table = g.CurrentTable)
2967
0
    {
2968
0
        if (table->IsInsideRow)
2969
0
            ImGui::TableEndRow(table);
2970
0
        table->RowPosY2 = window->DC.CursorPos.y;
2971
0
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2972
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2973
0
        table->RowBgColorCounter += row_increase;
2974
0
    }
2975
0
}
2976
2977
ImGuiListClipper::ImGuiListClipper()
2978
0
{
2979
0
    memset(this, 0, sizeof(*this));
2980
0
}
2981
2982
ImGuiListClipper::~ImGuiListClipper()
2983
0
{
2984
0
    End();
2985
0
}
2986
2987
void ImGuiListClipper::Begin(int items_count, float items_height)
2988
0
{
2989
0
    if (Ctx == NULL)
2990
0
        Ctx = ImGui::GetCurrentContext();
2991
2992
0
    ImGuiContext& g = *Ctx;
2993
0
    ImGuiWindow* window = g.CurrentWindow;
2994
0
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2995
2996
0
    if (ImGuiTable* table = g.CurrentTable)
2997
0
        if (table->IsInsideRow)
2998
0
            ImGui::TableEndRow(table);
2999
3000
0
    StartPosY = window->DC.CursorPos.y;
3001
0
    ItemsHeight = items_height;
3002
0
    ItemsCount = items_count;
3003
0
    DisplayStart = -1;
3004
0
    DisplayEnd = 0;
3005
3006
    // Acquire temporary buffer
3007
0
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
3008
0
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
3009
0
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3010
0
    data->Reset(this);
3011
0
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
3012
0
    TempData = data;
3013
0
    StartSeekOffsetY = data->LossynessOffset;
3014
0
}
3015
3016
void ImGuiListClipper::End()
3017
0
{
3018
0
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
3019
0
    {
3020
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
3021
0
        ImGuiContext& g = *Ctx;
3022
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
3023
0
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
3024
0
            SeekCursorForItem(ItemsCount);
3025
3026
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
3027
0
        IM_ASSERT(data->ListClipper == this);
3028
0
        data->StepNo = data->Ranges.Size;
3029
0
        if (--g.ClipperTempDataStacked > 0)
3030
0
        {
3031
0
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3032
0
            data->ListClipper->TempData = data;
3033
0
        }
3034
0
        TempData = NULL;
3035
0
    }
3036
0
    ItemsCount = -1;
3037
0
}
3038
3039
void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
3040
0
{
3041
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
3042
0
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
3043
0
    IM_ASSERT(item_begin <= item_end);
3044
0
    if (item_begin < item_end)
3045
0
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
3046
0
}
3047
3048
// This is already called while stepping.
3049
// The ONLY reason you may want to call this is if you passed INT_MAX to ImGuiListClipper::Begin() because you couldn't step item count beforehand.
3050
void ImGuiListClipper::SeekCursorForItem(int item_n)
3051
0
{
3052
    // - Perform the add and multiply with double to allow seeking through larger ranges.
3053
    // - StartPosY starts from ItemsFrozen, by adding SeekOffsetY we generally cancel that out (SeekOffsetY == LossynessOffset - ItemsFrozen * ItemsHeight).
3054
    // - The reason we store SeekOffsetY instead of inferring it, is because we want to allow user to perform Seek after the last step, where ImGuiListClipperData is already done.
3055
0
    float pos_y = (float)((double)StartPosY + StartSeekOffsetY + (double)item_n * ItemsHeight);
3056
0
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, ItemsHeight);
3057
0
}
3058
3059
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
3060
0
{
3061
0
    ImGuiContext& g = *clipper->Ctx;
3062
0
    ImGuiWindow* window = g.CurrentWindow;
3063
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
3064
0
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
3065
3066
0
    ImGuiTable* table = g.CurrentTable;
3067
0
    if (table && table->IsInsideRow)
3068
0
        ImGui::TableEndRow(table);
3069
3070
    // No items
3071
0
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
3072
0
        return false;
3073
3074
    // While we are in frozen row state, keep displaying items one by one, unclipped
3075
    // FIXME: Could be stored as a table-agnostic state.
3076
0
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
3077
0
    {
3078
0
        clipper->DisplayStart = data->ItemsFrozen;
3079
0
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
3080
0
        if (clipper->DisplayStart < clipper->DisplayEnd)
3081
0
            data->ItemsFrozen++;
3082
0
        return true;
3083
0
    }
3084
3085
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
3086
0
    bool calc_clipping = false;
3087
0
    if (data->StepNo == 0)
3088
0
    {
3089
0
        clipper->StartPosY = window->DC.CursorPos.y;
3090
0
        if (clipper->ItemsHeight <= 0.0f)
3091
0
        {
3092
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
3093
0
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
3094
0
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
3095
0
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
3096
0
            data->StepNo = 1;
3097
0
            return true;
3098
0
        }
3099
0
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
3100
0
    }
3101
3102
    // Step 1: Let the clipper infer height from first range
3103
0
    if (clipper->ItemsHeight <= 0.0f)
3104
0
    {
3105
0
        IM_ASSERT(data->StepNo == 1);
3106
0
        if (table)
3107
0
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
3108
3109
0
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
3110
0
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
3111
0
        if (affected_by_floating_point_precision)
3112
0
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
3113
3114
0
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
3115
0
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
3116
0
    }
3117
3118
    // Step 0 or 1: Calculate the actual ranges of visible elements.
3119
0
    const int already_submitted = clipper->DisplayEnd;
3120
0
    if (calc_clipping)
3121
0
    {
3122
        // Record seek offset, this is so ImGuiListClipper::Seek() can be called after ImGuiListClipperData is done
3123
0
        clipper->StartSeekOffsetY = (double)data->LossynessOffset - data->ItemsFrozen * (double)clipper->ItemsHeight;
3124
3125
0
        if (g.LogEnabled)
3126
0
        {
3127
            // If logging is active, do not perform any clipping
3128
0
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
3129
0
        }
3130
0
        else
3131
0
        {
3132
            // Add range selected to be included for navigation
3133
0
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3134
0
            if (is_nav_request)
3135
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
3136
0
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3137
0
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
3138
3139
            // Add focused/active item
3140
0
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
3141
0
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3142
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
3143
3144
            // Add visible range
3145
0
            float min_y = window->ClipRect.Min.y;
3146
0
            float max_y = window->ClipRect.Max.y;
3147
3148
            // Add box selection range
3149
0
            ImGuiBoxSelectState* bs = &g.BoxSelectState;
3150
0
            if (bs->IsActive && bs->Window == window)
3151
0
            {
3152
                // FIXME: Selectable() use of half-ItemSpacing isn't consistent in matter of layout, as ItemAdd(bb) stray above ItemSize()'s CursorPos.
3153
                // RangeSelect's BoxSelect relies on comparing overlap of previous and current rectangle and is sensitive to that.
3154
                // As a workaround we currently half ItemSpacing worth on each side.
3155
0
                min_y -= g.Style.ItemSpacing.y;
3156
0
                max_y += g.Style.ItemSpacing.y;
3157
3158
                // Box-select on 2D area requires different clipping.
3159
0
                if (bs->UnclipMode)
3160
0
                    data->Ranges.push_back(ImGuiListClipperRange::FromPositions(bs->UnclipRect.Min.y, bs->UnclipRect.Max.y, 0, 0));
3161
0
            }
3162
3163
0
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3164
0
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3165
0
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(min_y, max_y, off_min, off_max));
3166
0
        }
3167
3168
        // Convert position ranges to item index ranges
3169
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
3170
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3171
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3172
0
        for (ImGuiListClipperRange& range : data->Ranges)
3173
0
            if (range.PosToIndexConvert)
3174
0
            {
3175
0
                int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3176
0
                int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3177
0
                range.Min = ImClamp(already_submitted + m1 + range.PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
3178
0
                range.Max = ImClamp(already_submitted + m2 + range.PosToIndexOffsetMax, range.Min + 1, clipper->ItemsCount);
3179
0
                range.PosToIndexConvert = false;
3180
0
            }
3181
0
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
3182
0
    }
3183
3184
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3185
0
    while (data->StepNo < data->Ranges.Size)
3186
0
    {
3187
0
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
3188
0
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
3189
0
        if (clipper->DisplayStart > already_submitted) //-V1051
3190
0
            clipper->SeekCursorForItem(clipper->DisplayStart);
3191
0
        data->StepNo++;
3192
0
        if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size)
3193
0
            continue;
3194
0
        return true;
3195
0
    }
3196
3197
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3198
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3199
0
    if (clipper->ItemsCount < INT_MAX)
3200
0
        clipper->SeekCursorForItem(clipper->ItemsCount);
3201
3202
0
    return false;
3203
0
}
3204
3205
bool ImGuiListClipper::Step()
3206
0
{
3207
0
    ImGuiContext& g = *Ctx;
3208
0
    bool need_items_height = (ItemsHeight <= 0.0f);
3209
0
    bool ret = ImGuiListClipper_StepInternal(this);
3210
0
    if (ret && (DisplayStart == DisplayEnd))
3211
0
        ret = false;
3212
0
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3213
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3214
0
    if (need_items_height && ItemsHeight > 0.0f)
3215
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3216
0
    if (ret)
3217
0
    {
3218
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3219
0
    }
3220
0
    else
3221
0
    {
3222
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3223
0
        End();
3224
0
    }
3225
0
    return ret;
3226
0
}
3227
3228
//-----------------------------------------------------------------------------
3229
// [SECTION] STYLING
3230
//-----------------------------------------------------------------------------
3231
3232
ImGuiStyle& ImGui::GetStyle()
3233
122k
{
3234
122k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3235
122k
    return GImGui->Style;
3236
122k
}
3237
3238
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3239
749k
{
3240
749k
    ImGuiStyle& style = GImGui->Style;
3241
749k
    ImVec4 c = style.Colors[idx];
3242
749k
    c.w *= style.Alpha * alpha_mul;
3243
749k
    return ColorConvertFloat4ToU32(c);
3244
749k
}
3245
3246
ImU32 ImGui::GetColorU32(const ImVec4& col)
3247
0
{
3248
0
    ImGuiStyle& style = GImGui->Style;
3249
0
    ImVec4 c = col;
3250
0
    c.w *= style.Alpha;
3251
0
    return ColorConvertFloat4ToU32(c);
3252
0
}
3253
3254
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3255
0
{
3256
0
    ImGuiStyle& style = GImGui->Style;
3257
0
    return style.Colors[idx];
3258
0
}
3259
3260
ImU32 ImGui::GetColorU32(ImU32 col, float alpha_mul)
3261
0
{
3262
0
    ImGuiStyle& style = GImGui->Style;
3263
0
    alpha_mul *= style.Alpha;
3264
0
    if (alpha_mul >= 1.0f)
3265
0
        return col;
3266
0
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3267
0
    a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range.
3268
0
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3269
0
}
3270
3271
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3272
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3273
0
{
3274
0
    ImGuiContext& g = *GImGui;
3275
0
    ImGuiColorMod backup;
3276
0
    backup.Col = idx;
3277
0
    backup.BackupValue = g.Style.Colors[idx];
3278
0
    g.ColorStack.push_back(backup);
3279
0
    if (g.DebugFlashStyleColorIdx != idx)
3280
0
        g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3281
0
}
3282
3283
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3284
58.4k
{
3285
58.4k
    ImGuiContext& g = *GImGui;
3286
58.4k
    ImGuiColorMod backup;
3287
58.4k
    backup.Col = idx;
3288
58.4k
    backup.BackupValue = g.Style.Colors[idx];
3289
58.4k
    g.ColorStack.push_back(backup);
3290
58.4k
    if (g.DebugFlashStyleColorIdx != idx)
3291
58.4k
        g.Style.Colors[idx] = col;
3292
58.4k
}
3293
3294
void ImGui::PopStyleColor(int count)
3295
58.4k
{
3296
58.4k
    ImGuiContext& g = *GImGui;
3297
58.4k
    if (g.ColorStack.Size < count)
3298
0
    {
3299
0
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times!");
3300
0
        count = g.ColorStack.Size;
3301
0
    }
3302
116k
    while (count > 0)
3303
58.4k
    {
3304
58.4k
        ImGuiColorMod& backup = g.ColorStack.back();
3305
58.4k
        g.Style.Colors[backup.Col] = backup.BackupValue;
3306
58.4k
        g.ColorStack.pop_back();
3307
58.4k
        count--;
3308
58.4k
    }
3309
58.4k
}
3310
3311
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3312
{
3313
    ImGuiCol_Text, ImGuiCol_TabHovered, ImGuiCol_Tab, ImGuiCol_TabSelected, ImGuiCol_TabSelectedOverline, ImGuiCol_TabDimmed, ImGuiCol_TabDimmedSelected, ImGuiCol_TabDimmedSelectedOverline,
3314
};
3315
3316
static const ImGuiDataVarInfo GStyleVarInfo[] =
3317
{
3318
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, Alpha) },                     // ImGuiStyleVar_Alpha
3319
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) },             // ImGuiStyleVar_DisabledAlpha
3320
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowPadding) },             // ImGuiStyleVar_WindowPadding
3321
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowRounding) },            // ImGuiStyleVar_WindowRounding
3322
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) },          // ImGuiStyleVar_WindowBorderSize
3323
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowMinSize) },             // ImGuiStyleVar_WindowMinSize
3324
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) },          // ImGuiStyleVar_WindowTitleAlign
3325
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildRounding) },             // ImGuiStyleVar_ChildRounding
3326
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) },           // ImGuiStyleVar_ChildBorderSize
3327
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupRounding) },             // ImGuiStyleVar_PopupRounding
3328
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) },           // ImGuiStyleVar_PopupBorderSize
3329
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, FramePadding) },              // ImGuiStyleVar_FramePadding
3330
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameRounding) },             // ImGuiStyleVar_FrameRounding
3331
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) },           // ImGuiStyleVar_FrameBorderSize
3332
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemSpacing) },               // ImGuiStyleVar_ItemSpacing
3333
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) },          // ImGuiStyleVar_ItemInnerSpacing
3334
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, IndentSpacing) },             // ImGuiStyleVar_IndentSpacing
3335
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, CellPadding) },               // ImGuiStyleVar_CellPadding
3336
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) },             // ImGuiStyleVar_ScrollbarSize
3337
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) },         // ImGuiStyleVar_ScrollbarRounding
3338
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabMinSize) },               // ImGuiStyleVar_GrabMinSize
3339
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabRounding) },              // ImGuiStyleVar_GrabRounding
3340
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabRounding) },               // ImGuiStyleVar_TabRounding
3341
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBorderSize) },             // ImGuiStyleVar_TabBorderSize
3342
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) },          // ImGuiStyleVar_TabBarBorderSize
3343
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)},    // ImGuiStyleVar_TableAngledHeadersAngle
3344
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign
3345
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) },           // ImGuiStyleVar_ButtonTextAlign
3346
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) },       // ImGuiStyleVar_SelectableTextAlign
3347
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)},    // ImGuiStyleVar_SeparatorTextBorderSize
3348
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) },        // ImGuiStyleVar_SeparatorTextAlign
3349
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) },      // ImGuiStyleVar_SeparatorTextPadding
3350
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) },      // ImGuiStyleVar_DockingSeparatorSize
3351
};
3352
3353
const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3354
116k
{
3355
116k
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3356
116k
    IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3357
116k
    return &GStyleVarInfo[idx];
3358
116k
}
3359
3360
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3361
0
{
3362
0
    ImGuiContext& g = *GImGui;
3363
0
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3364
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3365
0
    {
3366
0
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3367
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3368
0
        *pvar = val;
3369
0
        return;
3370
0
    }
3371
0
    IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3372
0
}
3373
3374
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3375
58.4k
{
3376
58.4k
    ImGuiContext& g = *GImGui;
3377
58.4k
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3378
58.4k
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3379
58.4k
    {
3380
58.4k
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3381
58.4k
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3382
58.4k
        *pvar = val;
3383
58.4k
        return;
3384
58.4k
    }
3385
0
    IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3386
0
}
3387
3388
void ImGui::PopStyleVar(int count)
3389
58.4k
{
3390
58.4k
    ImGuiContext& g = *GImGui;
3391
58.4k
    if (g.StyleVarStack.Size < count)
3392
0
    {
3393
0
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times!");
3394
0
        count = g.StyleVarStack.Size;
3395
0
    }
3396
116k
    while (count > 0)
3397
58.4k
    {
3398
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3399
58.4k
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3400
58.4k
        const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3401
58.4k
        void* data = info->GetVarPtr(&g.Style);
3402
58.4k
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3403
58.4k
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3404
58.4k
        g.StyleVarStack.pop_back();
3405
58.4k
        count--;
3406
58.4k
    }
3407
58.4k
}
3408
3409
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3410
0
{
3411
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3412
0
    switch (idx)
3413
0
    {
3414
0
    case ImGuiCol_Text: return "Text";
3415
0
    case ImGuiCol_TextDisabled: return "TextDisabled";
3416
0
    case ImGuiCol_WindowBg: return "WindowBg";
3417
0
    case ImGuiCol_ChildBg: return "ChildBg";
3418
0
    case ImGuiCol_PopupBg: return "PopupBg";
3419
0
    case ImGuiCol_Border: return "Border";
3420
0
    case ImGuiCol_BorderShadow: return "BorderShadow";
3421
0
    case ImGuiCol_FrameBg: return "FrameBg";
3422
0
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3423
0
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3424
0
    case ImGuiCol_TitleBg: return "TitleBg";
3425
0
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3426
0
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3427
0
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3428
0
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3429
0
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3430
0
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3431
0
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3432
0
    case ImGuiCol_CheckMark: return "CheckMark";
3433
0
    case ImGuiCol_SliderGrab: return "SliderGrab";
3434
0
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3435
0
    case ImGuiCol_Button: return "Button";
3436
0
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3437
0
    case ImGuiCol_ButtonActive: return "ButtonActive";
3438
0
    case ImGuiCol_Header: return "Header";
3439
0
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3440
0
    case ImGuiCol_HeaderActive: return "HeaderActive";
3441
0
    case ImGuiCol_Separator: return "Separator";
3442
0
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3443
0
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3444
0
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3445
0
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3446
0
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3447
0
    case ImGuiCol_TabHovered: return "TabHovered";
3448
0
    case ImGuiCol_Tab: return "Tab";
3449
0
    case ImGuiCol_TabSelected: return "TabSelected";
3450
0
    case ImGuiCol_TabSelectedOverline: return "TabSelectedOverline";
3451
0
    case ImGuiCol_TabDimmed: return "TabDimmed";
3452
0
    case ImGuiCol_TabDimmedSelected: return "TabDimmedSelected";
3453
0
    case ImGuiCol_TabDimmedSelectedOverline: return "TabDimmedSelectedOverline";
3454
0
    case ImGuiCol_DockingPreview: return "DockingPreview";
3455
0
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3456
0
    case ImGuiCol_PlotLines: return "PlotLines";
3457
0
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3458
0
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3459
0
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3460
0
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3461
0
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3462
0
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3463
0
    case ImGuiCol_TableRowBg: return "TableRowBg";
3464
0
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3465
0
    case ImGuiCol_TextLink: return "TextLink";
3466
0
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3467
0
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3468
0
    case ImGuiCol_NavHighlight: return "NavHighlight";
3469
0
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3470
0
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3471
0
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3472
0
    }
3473
0
    IM_ASSERT(0);
3474
0
    return "Unknown";
3475
0
}
3476
3477
3478
//-----------------------------------------------------------------------------
3479
// [SECTION] RENDER HELPERS
3480
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3481
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3482
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3483
//-----------------------------------------------------------------------------
3484
3485
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3486
233k
{
3487
233k
    const char* text_display_end = text;
3488
233k
    if (!text_end)
3489
233k
        text_end = (const char*)-1;
3490
3491
2.10M
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3492
1.87M
        text_display_end++;
3493
233k
    return text_display_end;
3494
233k
}
3495
3496
// Internal ImGui functions to render text
3497
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3498
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3499
0
{
3500
0
    ImGuiContext& g = *GImGui;
3501
0
    ImGuiWindow* window = g.CurrentWindow;
3502
3503
    // Hide anything after a '##' string
3504
0
    const char* text_display_end;
3505
0
    if (hide_text_after_hash)
3506
0
    {
3507
0
        text_display_end = FindRenderedTextEnd(text, text_end);
3508
0
    }
3509
0
    else
3510
0
    {
3511
0
        if (!text_end)
3512
0
            text_end = text + strlen(text); // FIXME-OPT
3513
0
        text_display_end = text_end;
3514
0
    }
3515
3516
0
    if (text != text_display_end)
3517
0
    {
3518
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3519
0
        if (g.LogEnabled)
3520
0
            LogRenderedText(&pos, text, text_display_end);
3521
0
    }
3522
0
}
3523
3524
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3525
0
{
3526
0
    ImGuiContext& g = *GImGui;
3527
0
    ImGuiWindow* window = g.CurrentWindow;
3528
3529
0
    if (!text_end)
3530
0
        text_end = text + strlen(text); // FIXME-OPT
3531
3532
0
    if (text != text_end)
3533
0
    {
3534
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3535
0
        if (g.LogEnabled)
3536
0
            LogRenderedText(&pos, text, text_end);
3537
0
    }
3538
0
}
3539
3540
// Default clip_rect uses (pos_min,pos_max)
3541
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3542
// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3543
// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3544
// better advantage of the render function taking size into account for coarse clipping.
3545
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3546
116k
{
3547
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3548
116k
    ImVec2 pos = pos_min;
3549
116k
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3550
3551
116k
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3552
116k
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3553
116k
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3554
116k
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3555
116k
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3556
3557
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3558
116k
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3559
116k
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3560
3561
    // Render
3562
116k
    if (need_clipping)
3563
58.4k
    {
3564
58.4k
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3565
58.4k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3566
58.4k
    }
3567
58.4k
    else
3568
58.4k
    {
3569
58.4k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3570
58.4k
    }
3571
116k
}
3572
3573
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3574
116k
{
3575
    // Hide anything after a '##' string
3576
116k
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3577
116k
    const int text_len = (int)(text_display_end - text);
3578
116k
    if (text_len == 0)
3579
0
        return;
3580
3581
116k
    ImGuiContext& g = *GImGui;
3582
116k
    ImGuiWindow* window = g.CurrentWindow;
3583
116k
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3584
116k
    if (g.LogEnabled)
3585
0
        LogRenderedText(&pos_min, text, text_display_end);
3586
116k
}
3587
3588
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3589
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3590
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3591
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3592
0
{
3593
0
    ImGuiContext& g = *GImGui;
3594
0
    if (text_end_full == NULL)
3595
0
        text_end_full = FindRenderedTextEnd(text);
3596
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3597
3598
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3599
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3600
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3601
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3602
0
    if (text_size.x > pos_max.x - pos_min.x)
3603
0
    {
3604
        // Hello wo...
3605
        // |       |   |
3606
        // min   max   ellipsis_max
3607
        //          <-> this is generally some padding value
3608
3609
0
        const ImFont* font = draw_list->_Data->Font;
3610
0
        const float font_size = draw_list->_Data->FontSize;
3611
0
        const float font_scale = draw_list->_Data->FontScale;
3612
0
        const char* text_end_ellipsis = NULL;
3613
0
        const float ellipsis_width = font->EllipsisWidth * font_scale;
3614
3615
        // We can now claim the space between pos_max.x and ellipsis_max.x
3616
0
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3617
0
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3618
0
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3619
0
        {
3620
            // Always display at least 1 character if there's no room for character + ellipsis
3621
0
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3622
0
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3623
0
        }
3624
0
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3625
0
        {
3626
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3627
0
            text_end_ellipsis--;
3628
0
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3629
0
        }
3630
3631
        // Render text, render ellipsis
3632
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3633
0
        ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3634
0
        if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3635
0
            for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3636
0
                font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3637
0
    }
3638
0
    else
3639
0
    {
3640
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3641
0
    }
3642
3643
0
    if (g.LogEnabled)
3644
0
        LogRenderedText(&pos_min, text, text_end_full);
3645
0
}
3646
3647
// Render a rectangle shaped with optional rounding and borders
3648
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3649
48.2k
{
3650
48.2k
    ImGuiContext& g = *GImGui;
3651
48.2k
    ImGuiWindow* window = g.CurrentWindow;
3652
48.2k
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3653
48.2k
    const float border_size = g.Style.FrameBorderSize;
3654
48.2k
    if (border && border_size > 0.0f)
3655
48.2k
    {
3656
48.2k
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3657
48.2k
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3658
48.2k
    }
3659
48.2k
}
3660
3661
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3662
0
{
3663
0
    ImGuiContext& g = *GImGui;
3664
0
    ImGuiWindow* window = g.CurrentWindow;
3665
0
    const float border_size = g.Style.FrameBorderSize;
3666
0
    if (border_size > 0.0f)
3667
0
    {
3668
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3669
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3670
0
    }
3671
0
}
3672
3673
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3674
130k
{
3675
130k
    ImGuiContext& g = *GImGui;
3676
130k
    if (id != g.NavId)
3677
125k
        return;
3678
4.95k
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3679
357
        return;
3680
4.59k
    ImGuiWindow* window = g.CurrentWindow;
3681
4.59k
    if (window->DC.NavHideHighlightOneFrame)
3682
0
        return;
3683
3684
4.59k
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3685
4.59k
    ImRect display_rect = bb;
3686
4.59k
    display_rect.ClipWith(window->ClipRect);
3687
4.59k
    const float thickness = 2.0f;
3688
4.59k
    if (flags & ImGuiNavHighlightFlags_Compact)
3689
4.39k
    {
3690
4.39k
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
3691
4.39k
    }
3692
199
    else
3693
199
    {
3694
199
        const float distance = 3.0f + thickness * 0.5f;
3695
199
        display_rect.Expand(ImVec2(distance, distance));
3696
199
        bool fully_visible = window->ClipRect.Contains(display_rect);
3697
199
        if (!fully_visible)
3698
199
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3699
199
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
3700
199
        if (!fully_visible)
3701
199
            window->DrawList->PopClipRect();
3702
199
    }
3703
4.59k
}
3704
3705
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3706
0
{
3707
0
    ImGuiContext& g = *GImGui;
3708
0
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3709
0
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3710
0
    for (ImGuiViewportP* viewport : g.Viewports)
3711
0
    {
3712
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3713
0
        ImVec2 offset, size, uv[4];
3714
0
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3715
0
            continue;
3716
0
        const ImVec2 pos = base_pos - offset;
3717
0
        const float scale = base_scale * viewport->DpiScale;
3718
0
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3719
0
            continue;
3720
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3721
0
        ImTextureID tex_id = font_atlas->TexID;
3722
0
        draw_list->PushTextureID(tex_id);
3723
0
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3724
0
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3725
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3726
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3727
0
        draw_list->PopTextureID();
3728
0
    }
3729
0
}
3730
3731
//-----------------------------------------------------------------------------
3732
// [SECTION] INITIALIZATION, SHUTDOWN
3733
//-----------------------------------------------------------------------------
3734
3735
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3736
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3737
ImGuiContext* ImGui::GetCurrentContext()
3738
1
{
3739
1
    return GImGui;
3740
1
}
3741
3742
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3743
1
{
3744
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3745
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3746
#else
3747
1
    GImGui = ctx;
3748
1
#endif
3749
1
}
3750
3751
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3752
0
{
3753
0
    GImAllocatorAllocFunc = alloc_func;
3754
0
    GImAllocatorFreeFunc = free_func;
3755
0
    GImAllocatorUserData = user_data;
3756
0
}
3757
3758
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3759
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3760
0
{
3761
0
    *p_alloc_func = GImAllocatorAllocFunc;
3762
0
    *p_free_func = GImAllocatorFreeFunc;
3763
0
    *p_user_data = GImAllocatorUserData;
3764
0
}
3765
3766
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3767
1
{
3768
1
    ImGuiContext* prev_ctx = GetCurrentContext();
3769
1
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3770
1
    SetCurrentContext(ctx);
3771
1
    Initialize();
3772
1
    if (prev_ctx != NULL)
3773
0
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3774
1
    return ctx;
3775
1
}
3776
3777
void ImGui::DestroyContext(ImGuiContext* ctx)
3778
0
{
3779
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3780
0
    if (ctx == NULL) //-V1051
3781
0
        ctx = prev_ctx;
3782
0
    SetCurrentContext(ctx);
3783
0
    Shutdown();
3784
0
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3785
0
    IM_DELETE(ctx);
3786
0
}
3787
3788
// IMPORTANT: ###xxx suffixes must be same in ALL languages to allow for automation.
3789
static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3790
{
3791
    { ImGuiLocKey_VersionStr,           "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
3792
    { ImGuiLocKey_TableSizeOne,         "Size column to fit###SizeOne"          },
3793
    { ImGuiLocKey_TableSizeAllFit,      "Size all columns to fit###SizeAll"     },
3794
    { ImGuiLocKey_TableSizeAllDefault,  "Size all columns to default###SizeAll" },
3795
    { ImGuiLocKey_TableResetOrder,      "Reset order###ResetOrder"              },
3796
    { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)"                       },
3797
    { ImGuiLocKey_WindowingPopup,       "(Popup)"                               },
3798
    { ImGuiLocKey_WindowingUntitled,    "(Untitled)"                            },
3799
    { ImGuiLocKey_CopyLink,             "Copy Link###CopyLink"                  },
3800
    { ImGuiLocKey_DockingHideTabBar,    "Hide tab bar###HideTabBar"             },
3801
    { ImGuiLocKey_DockingHoldShiftToDock,       "Hold SHIFT to enable Docking window."  },
3802
    { ImGuiLocKey_DockingDragToUndockOrMoveNode,"Click and drag to move or undock whole node."    },
3803
};
3804
3805
void ImGui::Initialize()
3806
1
{
3807
1
    ImGuiContext& g = *GImGui;
3808
1
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3809
3810
    // Add .ini handle for ImGuiWindow and ImGuiTable types
3811
1
    {
3812
1
        ImGuiSettingsHandler ini_handler;
3813
1
        ini_handler.TypeName = "Window";
3814
1
        ini_handler.TypeHash = ImHashStr("Window");
3815
1
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3816
1
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3817
1
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3818
1
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3819
1
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3820
1
        AddSettingsHandler(&ini_handler);
3821
1
    }
3822
1
    TableSettingsAddSettingsHandler();
3823
3824
    // Setup default localization table
3825
1
    LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3826
3827
    // Setup default platform clipboard/IME handlers.
3828
1
    g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;    // Platform dependent default implementations
3829
1
    g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3830
1
    g.IO.ClipboardUserData = (void*)&g;                          // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3831
1
    g.IO.PlatformOpenInShellFn = PlatformOpenInShellFn_DefaultImpl;
3832
1
    g.IO.PlatformSetImeDataFn = PlatformSetImeDataFn_DefaultImpl;
3833
3834
    // Create default viewport
3835
1
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3836
1
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3837
1
    viewport->Idx = 0;
3838
1
    viewport->PlatformWindowCreated = true;
3839
1
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3840
1
    g.Viewports.push_back(viewport);
3841
1
    g.TempBuffer.resize(1024 * 3 + 1, 0);
3842
1
    g.ViewportCreatedCount++;
3843
1
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3844
3845
    // Build KeysMayBeCharInput[] lookup table (1 bool per named key)
3846
155
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
3847
154
        if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9)
3848
154
            || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period
3849
154
            || key == ImGuiKey_Slash || key == ImGuiKey_Semicolon || key == ImGuiKey_Equal || key == ImGuiKey_LeftBracket || key == ImGuiKey_RightBracket || key == ImGuiKey_GraveAccent
3850
154
            || key == ImGuiKey_KeypadDecimal || key == ImGuiKey_KeypadDivide || key == ImGuiKey_KeypadMultiply || key == ImGuiKey_KeypadSubtract || key == ImGuiKey_KeypadAdd || key == ImGuiKey_KeypadEqual)
3851
64
            g.KeysMayBeCharInput.SetBit(key);
3852
3853
1
#ifdef IMGUI_HAS_DOCK
3854
    // Initialize Docking
3855
1
    DockContextInitialize(&g);
3856
1
#endif
3857
3858
1
    g.Initialized = true;
3859
1
}
3860
3861
// This function is merely here to free heap allocations.
3862
void ImGui::Shutdown()
3863
0
{
3864
0
    ImGuiContext& g = *GImGui;
3865
0
    IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == NULL, "Forgot to shutdown Platform backend?");
3866
0
    IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?");
3867
3868
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3869
0
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3870
0
    {
3871
0
        g.IO.Fonts->Locked = false;
3872
0
        IM_DELETE(g.IO.Fonts);
3873
0
    }
3874
0
    g.IO.Fonts = NULL;
3875
0
    g.DrawListSharedData.TempBuffer.clear();
3876
3877
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3878
0
    if (!g.Initialized)
3879
0
        return;
3880
3881
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3882
0
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3883
0
        SaveIniSettingsToDisk(g.IO.IniFilename);
3884
3885
    // Destroy platform windows
3886
0
    DestroyPlatformWindows();
3887
3888
    // Shutdown extensions
3889
0
    DockContextShutdown(&g);
3890
3891
0
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3892
3893
    // Clear everything else
3894
0
    g.Windows.clear_delete();
3895
0
    g.WindowsFocusOrder.clear();
3896
0
    g.WindowsTempSortBuffer.clear();
3897
0
    g.CurrentWindow = NULL;
3898
0
    g.CurrentWindowStack.clear();
3899
0
    g.WindowsById.Clear();
3900
0
    g.NavWindow = NULL;
3901
0
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3902
0
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3903
0
    g.MovingWindow = NULL;
3904
3905
0
    g.KeysRoutingTable.Clear();
3906
3907
0
    g.ColorStack.clear();
3908
0
    g.StyleVarStack.clear();
3909
0
    g.FontStack.clear();
3910
0
    g.OpenPopupStack.clear();
3911
0
    g.BeginPopupStack.clear();
3912
0
    g.TreeNodeStack.clear();
3913
3914
0
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3915
0
    g.Viewports.clear_delete();
3916
3917
0
    g.TabBars.Clear();
3918
0
    g.CurrentTabBarStack.clear();
3919
0
    g.ShrinkWidthBuffer.clear();
3920
3921
0
    g.ClipperTempData.clear_destruct();
3922
3923
0
    g.Tables.Clear();
3924
0
    g.TablesTempData.clear_destruct();
3925
0
    g.DrawChannelsTempMergeBuffer.clear();
3926
3927
0
    g.MultiSelectStorage.Clear();
3928
0
    g.MultiSelectTempData.clear_destruct();
3929
3930
0
    g.ClipboardHandlerData.clear();
3931
0
    g.MenusIdSubmittedThisFrame.clear();
3932
0
    g.InputTextState.ClearFreeMemory();
3933
0
    g.InputTextDeactivatedState.ClearFreeMemory();
3934
3935
0
    g.SettingsWindows.clear();
3936
0
    g.SettingsHandlers.clear();
3937
3938
0
    if (g.LogFile)
3939
0
    {
3940
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3941
0
        if (g.LogFile != stdout)
3942
0
#endif
3943
0
            ImFileClose(g.LogFile);
3944
0
        g.LogFile = NULL;
3945
0
    }
3946
0
    g.LogBuffer.clear();
3947
0
    g.DebugLogBuf.clear();
3948
0
    g.DebugLogIndex.clear();
3949
3950
0
    g.Initialized = false;
3951
0
}
3952
3953
// No specific ordering/dependency support, will see as needed
3954
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3955
0
{
3956
0
    ImGuiContext& g = *ctx;
3957
0
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3958
0
    g.Hooks.push_back(*hook);
3959
0
    g.Hooks.back().HookId = ++g.HookIdNext;
3960
0
    return g.HookIdNext;
3961
0
}
3962
3963
// Deferred removal, avoiding issue with changing vector while iterating it
3964
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3965
0
{
3966
0
    ImGuiContext& g = *ctx;
3967
0
    IM_ASSERT(hook_id != 0);
3968
0
    for (ImGuiContextHook& hook : g.Hooks)
3969
0
        if (hook.HookId == hook_id)
3970
0
            hook.Type = ImGuiContextHookType_PendingRemoval_;
3971
0
}
3972
3973
// Call context hooks (used by e.g. test engine)
3974
// We assume a small number of hooks so all stored in same array
3975
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3976
350k
{
3977
350k
    ImGuiContext& g = *ctx;
3978
350k
    for (ImGuiContextHook& hook : g.Hooks)
3979
0
        if (hook.Type == hook_type)
3980
0
            hook.Callback(&g, &hook);
3981
350k
}
3982
3983
3984
//-----------------------------------------------------------------------------
3985
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3986
//-----------------------------------------------------------------------------
3987
3988
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3989
ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
3990
3
{
3991
3
    memset(this, 0, sizeof(*this));
3992
3
    Ctx = ctx;
3993
3
    Name = ImStrdup(name);
3994
3
    NameBufLen = (int)strlen(name) + 1;
3995
3
    ID = ImHashStr(name);
3996
3
    IDStack.push_back(ID);
3997
3
    ViewportAllowPlatformMonitorExtend = -1;
3998
3
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3999
3
    MoveId = GetID("#MOVE");
4000
3
    TabId = GetID("#TAB");
4001
3
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
4002
3
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
4003
3
    AutoFitFramesX = AutoFitFramesY = -1;
4004
3
    AutoPosLastDirection = ImGuiDir_None;
4005
3
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
4006
3
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
4007
3
    LastFrameActive = -1;
4008
3
    LastFrameJustFocused = -1;
4009
3
    LastTimeActive = -1.0f;
4010
3
    FontWindowScale = FontDpiScale = 1.0f;
4011
3
    SettingsOffset = -1;
4012
3
    DockOrder = -1;
4013
3
    DrawList = &DrawListInst;
4014
3
    DrawList->_Data = &Ctx->DrawListSharedData;
4015
3
    DrawList->_OwnerName = Name;
4016
3
    NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
4017
3
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
4018
3
}
4019
4020
ImGuiWindow::~ImGuiWindow()
4021
0
{
4022
0
    IM_ASSERT(DrawList == &DrawListInst);
4023
0
    IM_DELETE(Name);
4024
0
    ColumnsStorage.clear_destruct();
4025
0
}
4026
4027
static void SetCurrentWindow(ImGuiWindow* window)
4028
254k
{
4029
254k
    ImGuiContext& g = *GImGui;
4030
254k
    g.CurrentWindow = window;
4031
254k
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
4032
254k
    if (window)
4033
195k
    {
4034
195k
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
4035
195k
        g.FontScale = g.FontSize / g.Font->FontSize;
4036
195k
        ImGui::NavUpdateCurrentWindowIsScrollPushableX();
4037
195k
    }
4038
254k
}
4039
4040
void ImGui::GcCompactTransientMiscBuffers()
4041
0
{
4042
0
    ImGuiContext& g = *GImGui;
4043
0
    g.ItemFlagsStack.clear();
4044
0
    g.GroupStack.clear();
4045
0
    g.MultiSelectTempDataStacked = 0;
4046
0
    g.MultiSelectTempData.clear_destruct();
4047
0
    TableGcCompactSettings();
4048
0
}
4049
4050
// Free up/compact internal window buffers, we can use this when a window becomes unused.
4051
// Not freed:
4052
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
4053
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
4054
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
4055
1
{
4056
1
    window->MemoryCompacted = true;
4057
1
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
4058
1
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
4059
1
    window->IDStack.clear();
4060
1
    window->DrawList->_ClearFreeMemory();
4061
1
    window->DC.ChildWindows.clear();
4062
1
    window->DC.ItemWidthStack.clear();
4063
1
    window->DC.TextWrapPosStack.clear();
4064
1
}
4065
4066
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
4067
0
{
4068
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
4069
    // The other buffers tends to amortize much faster.
4070
0
    window->MemoryCompacted = false;
4071
0
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
4072
0
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
4073
0
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
4074
0
}
4075
4076
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
4077
121
{
4078
121
    ImGuiContext& g = *GImGui;
4079
4080
    // Clear previous active id
4081
121
    if (g.ActiveId != 0)
4082
15
    {
4083
        // While most behaved code would make an effort to not steal active id during window move/drag operations,
4084
        // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
4085
        // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
4086
15
        if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
4087
0
        {
4088
0
            IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
4089
0
            g.MovingWindow = NULL;
4090
0
        }
4091
4092
        // This could be written in a more general way (e.g associate a hook to ActiveId),
4093
        // but since this is currently quite an exception we'll leave it as is.
4094
        // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
4095
15
        if (g.InputTextState.ID == g.ActiveId)
4096
0
            InputTextDeactivateHook(g.ActiveId);
4097
15
    }
4098
4099
    // Set active id
4100
121
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
4101
121
    if (g.ActiveIdIsJustActivated)
4102
29
    {
4103
29
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
4104
29
        g.ActiveIdTimer = 0.0f;
4105
29
        g.ActiveIdHasBeenPressedBefore = false;
4106
29
        g.ActiveIdHasBeenEditedBefore = false;
4107
29
        g.ActiveIdMouseButton = -1;
4108
29
        if (id != 0)
4109
15
        {
4110
15
            g.LastActiveId = id;
4111
15
            g.LastActiveIdTimer = 0.0f;
4112
15
        }
4113
29
    }
4114
121
    g.ActiveId = id;
4115
121
    g.ActiveIdAllowOverlap = false;
4116
121
    g.ActiveIdNoClearOnFocusLoss = false;
4117
121
    g.ActiveIdWindow = window;
4118
121
    g.ActiveIdHasBeenEditedThisFrame = false;
4119
121
    g.ActiveIdFromShortcut = false;
4120
121
    if (id)
4121
15
    {
4122
15
        g.ActiveIdIsAlive = id;
4123
15
        g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
4124
15
        IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
4125
15
    }
4126
4127
    // Clear declaration of inputs claimed by the widget
4128
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
4129
121
    g.ActiveIdUsingNavDirMask = 0x00;
4130
121
    g.ActiveIdUsingAllKeyboardKeys = false;
4131
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4132
    g.ActiveIdUsingNavInputMask = 0x00;
4133
#endif
4134
121
}
4135
4136
void ImGui::ClearActiveID()
4137
106
{
4138
106
    SetActiveID(0, NULL); // g.ActiveId = 0;
4139
106
}
4140
4141
void ImGui::SetHoveredID(ImGuiID id)
4142
9
{
4143
9
    ImGuiContext& g = *GImGui;
4144
9
    g.HoveredId = id;
4145
9
    g.HoveredIdAllowOverlap = false;
4146
9
    if (id != 0 && g.HoveredIdPreviousFrame != id)
4147
7
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
4148
9
}
4149
4150
ImGuiID ImGui::GetHoveredID()
4151
0
{
4152
0
    ImGuiContext& g = *GImGui;
4153
0
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4154
0
}
4155
4156
void ImGui::MarkItemEdited(ImGuiID id)
4157
0
{
4158
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
4159
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
4160
0
    ImGuiContext& g = *GImGui;
4161
0
    if (g.LockMarkEdited > 0)
4162
0
        return;
4163
0
    if (g.ActiveId == id || g.ActiveId == 0)
4164
0
    {
4165
0
        g.ActiveIdHasBeenEditedThisFrame = true;
4166
0
        g.ActiveIdHasBeenEditedBefore = true;
4167
0
    }
4168
4169
    // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4170
    // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4171
0
    IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id || (g.CurrentMultiSelect != NULL && g.BoxSelectState.IsActive));
4172
4173
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4174
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4175
0
}
4176
4177
bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4178
10
{
4179
    // An active popup disable hovering on other windows (apart from its own children)
4180
    // FIXME-OPT: This could be cached/stored within the window.
4181
10
    ImGuiContext& g = *GImGui;
4182
10
    if (g.NavWindow)
4183
0
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4184
0
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4185
0
            {
4186
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4187
                // NB: The 'else' is important because Modal windows are also Popups.
4188
0
                bool want_inhibit = false;
4189
0
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4190
0
                    want_inhibit = true;
4191
0
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4192
0
                    want_inhibit = true;
4193
4194
                // Inhibit hover unless the window is within the stack of our modal/popup
4195
0
                if (want_inhibit)
4196
0
                    if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4197
0
                        return false;
4198
0
            }
4199
4200
    // Filter by viewport
4201
10
    if (window->Viewport != g.MouseViewport)
4202
0
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4203
0
            return false;
4204
4205
10
    return true;
4206
10
}
4207
4208
static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4209
0
{
4210
0
    ImGuiContext& g = *GImGui;
4211
0
    if (flags & ImGuiHoveredFlags_DelayNormal)
4212
0
        return g.Style.HoverDelayNormal;
4213
0
    if (flags & ImGuiHoveredFlags_DelayShort)
4214
0
        return g.Style.HoverDelayShort;
4215
0
    return 0.0f;
4216
0
}
4217
4218
static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4219
0
{
4220
    // Allow instance flags to override shared flags
4221
0
    if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4222
0
        shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4223
0
    return user_flags | shared_flags;
4224
0
}
4225
4226
// This is roughly matching the behavior of internal-facing ItemHoverable()
4227
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
4228
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4229
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4230
0
{
4231
0
    ImGuiContext& g = *GImGui;
4232
0
    ImGuiWindow* window = g.CurrentWindow;
4233
0
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0 && "Invalid flags for IsItemHovered()!");
4234
4235
0
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
4236
0
    {
4237
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4238
0
            return false;
4239
0
        if (!IsItemFocused())
4240
0
            return false;
4241
4242
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4243
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav);
4244
0
    }
4245
0
    else
4246
0
    {
4247
        // Test for bounding box overlap, as updated as ItemAdd()
4248
0
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4249
0
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4250
0
            return false;
4251
4252
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4253
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
4254
4255
0
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
4256
4257
        // Done with rectangle culling so we can perform heavier checks now
4258
        // Test if we are hovering the right window (our window could be behind another window)
4259
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4260
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
4261
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
4262
        // the test that has been running for a long while.
4263
0
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4264
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4265
0
                return false;
4266
4267
        // Test if another item is active (e.g. being dragged)
4268
0
        const ImGuiID id = g.LastItemData.ID;
4269
0
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4270
0
            if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4271
0
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
4272
0
                    return false;
4273
4274
        // Test if interactions on this window are blocked by an active popup or modal.
4275
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4276
0
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4277
0
            return false;
4278
4279
        // Test if the item is disabled
4280
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4281
0
            return false;
4282
4283
        // Special handling for calling after Begin() which represent the title bar or tab.
4284
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4285
        // will never be overwritten so we need to detect the case.
4286
0
        if (id == window->MoveId && window->WriteAccessed)
4287
0
            return false;
4288
4289
        // Test if using AllowOverlap and overlapped
4290
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4291
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4292
0
                if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4293
0
                    return false;
4294
0
    }
4295
4296
    // Handle hover delay
4297
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4298
0
    const float delay = CalcDelayFromHoveredFlags(flags);
4299
0
    if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4300
0
    {
4301
0
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4302
0
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4303
0
            g.HoverItemDelayTimer = 0.0f;
4304
0
        g.HoverItemDelayId = hover_delay_id;
4305
4306
        // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4307
        // but once unlocked on a given item we also moving.
4308
        //if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); }
4309
0
        if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4310
0
            return false;
4311
4312
0
        if (g.HoverItemDelayTimer < delay)
4313
0
            return false;
4314
0
    }
4315
4316
0
    return true;
4317
0
}
4318
4319
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4320
// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4321
// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4322
// If you used this in your legacy/custom widgets code:
4323
// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.InFlags'.
4324
// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4325
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4326
184k
{
4327
184k
    ImGuiContext& g = *GImGui;
4328
184k
    ImGuiWindow* window = g.CurrentWindow;
4329
184k
    if (g.HoveredWindow != window)
4330
184k
        return false;
4331
458
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
4332
449
        return false;
4333
4334
9
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4335
0
        return false;
4336
9
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4337
0
        if (!g.ActiveIdFromShortcut)
4338
0
            return false;
4339
4340
    // Done with rectangle culling so we can perform heavier checks now.
4341
9
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4342
0
    {
4343
0
        g.HoveredIdIsDisabled = true;
4344
0
        return false;
4345
0
    }
4346
4347
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4348
    // hover test in widgets code. We could also decide to split this function is two.
4349
9
    if (id != 0)
4350
9
    {
4351
        // Drag source doesn't report as hovered
4352
9
        if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4353
0
            return false;
4354
4355
9
        SetHoveredID(id);
4356
4357
        // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4358
        // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4359
9
        if (item_flags & ImGuiItemFlags_AllowOverlap)
4360
0
        {
4361
0
            g.HoveredIdAllowOverlap = true;
4362
0
            if (g.HoveredIdPreviousFrame != id)
4363
0
                return false;
4364
0
        }
4365
4366
        // Display shortcut (only works with mouse)
4367
        // (ImGuiItemStatusFlags_HasShortcut in LastItemData denotes we want a tooltip)
4368
9
        if (id == g.LastItemData.ID && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasShortcut))
4369
0
            if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal))
4370
0
                SetTooltip("%s", GetKeyChordName(g.LastItemData.Shortcut));
4371
9
    }
4372
4373
    // When disabled we'll return false but still set HoveredId
4374
9
    if (item_flags & ImGuiItemFlags_Disabled)
4375
0
    {
4376
        // Release active id if turning disabled
4377
0
        if (g.ActiveId == id && id != 0)
4378
0
            ClearActiveID();
4379
0
        g.HoveredIdIsDisabled = true;
4380
0
        return false;
4381
0
    }
4382
4383
9
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4384
9
    if (id != 0)
4385
9
    {
4386
        // [DEBUG] Item Picker tool!
4387
        // We perform the check here because reaching is path is rare (1~ time a frame),
4388
        // making the cost of this tool near-zero! We could get better call-stack and support picking non-hovered
4389
        // items if we performed the test in ItemAdd(), but that would incur a bigger runtime cost.
4390
9
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4391
0
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4392
9
        if (g.DebugItemPickerBreakId == id)
4393
0
            IM_DEBUG_BREAK();
4394
9
    }
4395
9
#endif
4396
4397
9
    if (g.NavDisableMouseHover)
4398
0
        return false;
4399
4400
9
    return true;
4401
9
}
4402
4403
// FIXME: This is inlined/duplicated in ItemAdd()
4404
// FIXME: The id != 0 path is not used by our codebase, may get rid of it?
4405
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4406
0
{
4407
0
    ImGuiContext& g = *GImGui;
4408
0
    ImGuiWindow* window = g.CurrentWindow;
4409
0
    if (!bb.Overlaps(window->ClipRect))
4410
0
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
4411
0
            if (!g.ItemUnclipByLog)
4412
0
                return true;
4413
0
    return false;
4414
0
}
4415
4416
// This is also inlined in ItemAdd()
4417
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4418
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4419
127k
{
4420
127k
    ImGuiContext& g = *GImGui;
4421
127k
    g.LastItemData.ID = item_id;
4422
127k
    g.LastItemData.InFlags = in_flags;
4423
127k
    g.LastItemData.StatusFlags = item_flags;
4424
127k
    g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4425
127k
}
4426
4427
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4428
0
{
4429
0
    if (wrap_pos_x < 0.0f)
4430
0
        return 0.0f;
4431
4432
0
    ImGuiContext& g = *GImGui;
4433
0
    ImGuiWindow* window = g.CurrentWindow;
4434
0
    if (wrap_pos_x == 0.0f)
4435
0
    {
4436
        // We could decide to setup a default wrapping max point for auto-resizing windows,
4437
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4438
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4439
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4440
        //else
4441
0
        wrap_pos_x = window->WorkRect.Max.x;
4442
0
    }
4443
0
    else if (wrap_pos_x > 0.0f)
4444
0
    {
4445
0
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4446
0
    }
4447
4448
0
    return ImMax(wrap_pos_x - pos.x, 1.0f);
4449
0
}
4450
4451
// IM_ALLOC() == ImGui::MemAlloc()
4452
void* ImGui::MemAlloc(size_t size)
4453
1.20k
{
4454
1.20k
    void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4455
1.20k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4456
1.20k
    if (ImGuiContext* ctx = GImGui)
4457
1.20k
        DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, size);
4458
1.20k
#endif
4459
1.20k
    return ptr;
4460
1.20k
}
4461
4462
// IM_FREE() == ImGui::MemFree()
4463
void ImGui::MemFree(void* ptr)
4464
1.15k
{
4465
1.15k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4466
1.15k
    if (ptr != NULL)
4467
1.15k
        if (ImGuiContext* ctx = GImGui)
4468
1.15k
            DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, (size_t)-1);
4469
1.15k
#endif
4470
1.15k
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4471
1.15k
}
4472
4473
// We record the number of allocation in recent frames, as a way to audit/sanitize our guiding principles of "no allocations on idle/repeating frames"
4474
void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
4475
2.35k
{
4476
2.35k
    ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4477
2.35k
    IM_UNUSED(ptr);
4478
2.35k
    if (entry->FrameCount != frame_count)
4479
25
    {
4480
25
        info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
4481
25
        entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4482
25
        entry->FrameCount = frame_count;
4483
25
        entry->AllocCount = entry->FreeCount = 0;
4484
25
    }
4485
2.35k
    if (size != (size_t)-1)
4486
1.20k
    {
4487
1.20k
        entry->AllocCount++;
4488
1.20k
        info->TotalAllocCount++;
4489
        //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, size, ptr);
4490
1.20k
    }
4491
1.15k
    else
4492
1.15k
    {
4493
1.15k
        entry->FreeCount++;
4494
1.15k
        info->TotalFreeCount++;
4495
        //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
4496
1.15k
    }
4497
2.35k
}
4498
4499
const char* ImGui::GetClipboardText()
4500
0
{
4501
0
    ImGuiContext& g = *GImGui;
4502
0
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4503
0
}
4504
4505
void ImGui::SetClipboardText(const char* text)
4506
0
{
4507
0
    ImGuiContext& g = *GImGui;
4508
0
    if (g.IO.SetClipboardTextFn)
4509
0
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4510
0
}
4511
4512
const char* ImGui::GetVersion()
4513
0
{
4514
0
    return IMGUI_VERSION;
4515
0
}
4516
4517
ImGuiIO& ImGui::GetIO()
4518
173k
{
4519
173k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4520
173k
    return GImGui->IO;
4521
173k
}
4522
4523
ImGuiPlatformIO& ImGui::GetPlatformIO()
4524
0
{
4525
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext()?");
4526
0
    return GImGui->PlatformIO;
4527
0
}
4528
4529
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4530
ImDrawData* ImGui::GetDrawData()
4531
58.4k
{
4532
58.4k
    ImGuiContext& g = *GImGui;
4533
58.4k
    ImGuiViewportP* viewport = g.Viewports[0];
4534
58.4k
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4535
58.4k
}
4536
4537
double ImGui::GetTime()
4538
1
{
4539
1
    return GImGui->Time;
4540
1
}
4541
4542
int ImGui::GetFrameCount()
4543
0
{
4544
0
    return GImGui->FrameCount;
4545
0
}
4546
4547
static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4548
0
{
4549
    // Create the draw list on demand, because they are not frequently used for all viewports
4550
0
    ImGuiContext& g = *GImGui;
4551
0
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
4552
0
    ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
4553
0
    if (draw_list == NULL)
4554
0
    {
4555
0
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4556
0
        draw_list->_OwnerName = drawlist_name;
4557
0
        viewport->BgFgDrawLists[drawlist_no] = draw_list;
4558
0
    }
4559
4560
    // Our ImDrawList system requires that there is always a command
4561
0
    if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
4562
0
    {
4563
0
        draw_list->_ResetForNewFrame();
4564
0
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4565
0
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4566
0
        viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
4567
0
    }
4568
0
    return draw_list;
4569
0
}
4570
4571
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4572
0
{
4573
0
    if (viewport == NULL)
4574
0
        viewport = GImGui->CurrentWindow->Viewport;
4575
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4576
0
}
4577
4578
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4579
0
{
4580
0
    if (viewport == NULL)
4581
0
        viewport = GImGui->CurrentWindow->Viewport;
4582
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4583
0
}
4584
4585
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4586
0
{
4587
0
    return &GImGui->DrawListSharedData;
4588
0
}
4589
4590
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4591
2
{
4592
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4593
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4594
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4595
2
    ImGuiContext& g = *GImGui;
4596
2
    FocusWindow(window);
4597
2
    SetActiveID(window->MoveId, window);
4598
2
    g.NavDisableHighlight = true;
4599
2
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4600
2
    g.ActiveIdNoClearOnFocusLoss = true;
4601
2
    SetActiveIdUsingAllKeyboardKeys();
4602
4603
2
    bool can_move_window = true;
4604
2
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4605
0
        can_move_window = false;
4606
2
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4607
0
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4608
0
            can_move_window = false;
4609
2
    if (can_move_window)
4610
2
        g.MovingWindow = window;
4611
2
}
4612
4613
// We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4614
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock)
4615
1
{
4616
1
    ImGuiContext& g = *GImGui;
4617
1
    bool can_undock_node = false;
4618
1
    if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0)
4619
0
    {
4620
        // Can undock if:
4621
        // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window)
4622
        // - part of a dockspace node hierarchy: so we can undock the last single visible node too (trivia: undocking from a fixed/central node will create a new node and copy windows)
4623
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4624
0
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4625
0
            can_undock_node = true;
4626
0
    }
4627
4628
1
    const bool clicked = IsMouseClicked(0);
4629
1
    const bool dragging = IsMouseDragging(0);
4630
1
    if (can_undock_node && dragging)
4631
0
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4632
1
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4633
1
        StartMouseMovingWindow(window);
4634
1
}
4635
4636
// Handle mouse moving window
4637
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4638
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4639
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4640
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4641
void ImGui::UpdateMouseMovingWindowNewFrame()
4642
58.4k
{
4643
58.4k
    ImGuiContext& g = *GImGui;
4644
58.4k
    if (g.MovingWindow != NULL)
4645
92
    {
4646
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4647
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4648
92
        KeepAliveID(g.ActiveId);
4649
92
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4650
92
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4651
4652
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4653
92
        const bool window_disappared = (!moving_window->WasActive && !moving_window->Active);
4654
92
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4655
90
        {
4656
90
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4657
90
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4658
53
            {
4659
53
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4660
53
                if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4661
0
                {
4662
0
                    moving_window->Viewport->Pos = pos;
4663
0
                    moving_window->Viewport->UpdateWorkRect();
4664
0
                }
4665
53
            }
4666
90
            FocusWindow(g.MovingWindow);
4667
90
        }
4668
2
        else
4669
2
        {
4670
2
            if (!window_disappared)
4671
2
            {
4672
                // Try to merge the window back into the main viewport.
4673
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4674
2
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4675
0
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4676
4677
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4678
2
                if (moving_window->Viewport && !IsDragDropPayloadBeingAccepted())
4679
2
                    g.MouseViewport = moving_window->Viewport;
4680
4681
                // Clear the NoInput window flag set by the Viewport system
4682
2
                if (moving_window->Viewport)
4683
2
                    moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
4684
2
            }
4685
4686
2
            g.MovingWindow = NULL;
4687
2
            ClearActiveID();
4688
2
        }
4689
92
    }
4690
58.3k
    else
4691
58.3k
    {
4692
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4693
58.3k
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4694
0
        {
4695
0
            KeepAliveID(g.ActiveId);
4696
0
            if (!g.IO.MouseDown[0])
4697
0
                ClearActiveID();
4698
0
        }
4699
58.3k
    }
4700
58.4k
}
4701
4702
// Initiate moving window when clicking on empty space or title bar.
4703
// Handle left-click and right-click focus.
4704
void ImGui::UpdateMouseMovingWindowEndFrame()
4705
58.4k
{
4706
58.4k
    ImGuiContext& g = *GImGui;
4707
58.4k
    if (g.ActiveId != 0 || g.HoveredId != 0)
4708
112
        return;
4709
4710
    // Unless we just made a window/popup appear
4711
58.3k
    if (g.NavWindow && g.NavWindow->Appearing)
4712
1
        return;
4713
4714
    // Click on empty space to focus window and start moving
4715
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4716
58.3k
    if (g.IO.MouseClicked[0])
4717
1.63k
    {
4718
        // Handle the edge case of a popup being closed while clicking in its empty space.
4719
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4720
1.63k
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4721
1.63k
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4722
4723
1.63k
        if (root_window != NULL && !is_closed_popup)
4724
1
        {
4725
1
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4726
4727
            // Cancel moving if clicked outside of title bar
4728
1
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4729
0
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4730
0
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4731
0
                        g.MovingWindow = NULL;
4732
4733
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4734
1
            if (g.HoveredIdIsDisabled)
4735
0
                g.MovingWindow = NULL;
4736
1
        }
4737
1.63k
        else if (root_window == NULL && g.NavWindow != NULL)
4738
42
        {
4739
            // Clicking on void disable focus
4740
42
            FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
4741
42
        }
4742
1.63k
    }
4743
4744
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4745
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4746
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4747
58.3k
    if (g.IO.MouseClicked[1])
4748
358
    {
4749
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4750
        // This is where we can trim the popup stack.
4751
358
        ImGuiWindow* modal = GetTopMostPopupModal();
4752
358
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4753
358
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4754
358
    }
4755
58.3k
}
4756
4757
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4758
// Need to keep in sync with SetWindowPos()
4759
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4760
0
{
4761
0
    window->Pos += delta;
4762
0
    window->ClipRect.Translate(delta);
4763
0
    window->OuterRectClipped.Translate(delta);
4764
0
    window->InnerRect.Translate(delta);
4765
0
    window->DC.CursorPos += delta;
4766
0
    window->DC.CursorStartPos += delta;
4767
0
    window->DC.CursorMaxPos += delta;
4768
0
    window->DC.IdealMaxPos += delta;
4769
0
}
4770
4771
static void ScaleWindow(ImGuiWindow* window, float scale)
4772
0
{
4773
0
    ImVec2 origin = window->Viewport->Pos;
4774
0
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4775
0
    window->Size = ImTrunc(window->Size * scale);
4776
0
    window->SizeFull = ImTrunc(window->SizeFull * scale);
4777
0
    window->ContentSize = ImTrunc(window->ContentSize * scale);
4778
0
}
4779
4780
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4781
185k
{
4782
185k
    return (window->Active) && (!window->Hidden);
4783
185k
}
4784
4785
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4786
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4787
58.4k
{
4788
58.4k
    ImGuiContext& g = *GImGui;
4789
58.4k
    ImGuiIO& io = g.IO;
4790
4791
    // FIXME-DPI: This storage was added on 2021/03/31 for test engine, but if we want to multiply WINDOWS_HOVER_PADDING
4792
    // by DpiScale, we need to make this window-agnostic anyhow, maybe need storing inside ImGuiWindow.
4793
58.4k
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4794
4795
    // Find the window hovered by mouse:
4796
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4797
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4798
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4799
58.4k
    bool clear_hovered_windows = false;
4800
58.4k
    FindHoveredWindowEx(g.IO.MousePos, false, &g.HoveredWindow, &g.HoveredWindowUnderMovingWindow);
4801
58.4k
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4802
58.4k
    g.HoveredWindowBeforeClear = g.HoveredWindow;
4803
4804
    // Modal windows prevents mouse from hovering behind them.
4805
58.4k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4806
58.4k
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4807
0
        clear_hovered_windows = true;
4808
4809
    // Disabled mouse hovering (we don't currently clear MousePos, we could)
4810
58.4k
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4811
0
        clear_hovered_windows = true;
4812
4813
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4814
    // won't report hovering nor request capture even while dragging over our windows afterward.
4815
58.4k
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4816
58.4k
    const bool has_open_modal = (modal_window != NULL);
4817
58.4k
    int mouse_earliest_down = -1;
4818
58.4k
    bool mouse_any_down = false;
4819
350k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4820
292k
    {
4821
292k
        if (io.MouseClicked[i])
4822
3.58k
        {
4823
3.58k
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4824
3.58k
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4825
3.58k
        }
4826
292k
        mouse_any_down |= io.MouseDown[i];
4827
292k
        if (io.MouseDown[i] || io.MouseReleased[i]) // Increase release frame for our evaluation of earliest button (#1392)
4828
83.9k
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4829
63.9k
                mouse_earliest_down = i;
4830
292k
    }
4831
58.4k
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4832
58.4k
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4833
4834
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4835
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4836
58.4k
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4837
58.4k
    if (!mouse_avail && !mouse_dragging_extern_payload)
4838
46.4k
        clear_hovered_windows = true;
4839
4840
58.4k
    if (clear_hovered_windows)
4841
46.4k
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4842
4843
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4844
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4845
58.4k
    if (g.WantCaptureMouseNextFrame != -1)
4846
0
    {
4847
0
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4848
0
    }
4849
58.4k
    else
4850
58.4k
    {
4851
58.4k
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4852
58.4k
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4853
58.4k
    }
4854
4855
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4856
58.4k
    io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4857
58.4k
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4858
3.54k
        io.WantCaptureKeyboard = true;
4859
58.4k
    if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
4860
0
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4861
4862
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4863
58.4k
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4864
58.4k
}
4865
4866
// Calling SetupDrawListSharedData() is followed by SetCurrentFont() which sets up the remaining data.
4867
static void SetupDrawListSharedData()
4868
58.4k
{
4869
58.4k
    ImGuiContext& g = *GImGui;
4870
58.4k
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4871
58.4k
    for (ImGuiViewportP* viewport : g.Viewports)
4872
58.4k
        virtual_space.Add(viewport->GetMainRect());
4873
58.4k
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4874
58.4k
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4875
58.4k
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4876
58.4k
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4877
58.4k
    if (g.Style.AntiAliasedLines)
4878
58.4k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4879
58.4k
    if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines))
4880
58.4k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4881
58.4k
    if (g.Style.AntiAliasedFill)
4882
58.4k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4883
58.4k
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4884
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4885
58.4k
}
4886
4887
void ImGui::NewFrame()
4888
58.4k
{
4889
58.4k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4890
58.4k
    ImGuiContext& g = *GImGui;
4891
4892
    // Remove pending delete hooks before frame start.
4893
    // This deferred removal avoid issues of removal while iterating the hook vector
4894
58.4k
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4895
0
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4896
0
            g.Hooks.erase(&g.Hooks[n]);
4897
4898
58.4k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4899
4900
    // Check and assert for various common IO and Configuration mistakes
4901
58.4k
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4902
58.4k
    ErrorCheckNewFrameSanityChecks();
4903
58.4k
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4904
4905
    // Load settings on first frame, save settings when modified (after a delay)
4906
58.4k
    UpdateSettings();
4907
4908
58.4k
    g.Time += g.IO.DeltaTime;
4909
58.4k
    g.WithinFrameScope = true;
4910
58.4k
    g.FrameCount += 1;
4911
58.4k
    g.TooltipOverrideCount = 0;
4912
58.4k
    g.WindowsActiveCount = 0;
4913
58.4k
    g.MenusIdSubmittedThisFrame.resize(0);
4914
4915
    // Calculate frame-rate for the user, as a purely luxurious feature
4916
58.4k
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4917
58.4k
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4918
58.4k
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4919
58.4k
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4920
58.4k
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4921
4922
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4923
58.4k
    g.InputEventsTrail.resize(0);
4924
58.4k
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4925
4926
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4927
58.4k
    UpdateViewportsNewFrame();
4928
4929
    // Setup current font and draw list shared data
4930
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4931
58.4k
    g.IO.Fonts->Locked = true;
4932
58.4k
    SetupDrawListSharedData();
4933
58.4k
    SetCurrentFont(GetDefaultFont());
4934
58.4k
    IM_ASSERT(g.Font->IsLoaded());
4935
4936
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4937
58.4k
    for (ImGuiViewportP* viewport : g.Viewports)
4938
58.4k
    {
4939
58.4k
        viewport->DrawData = NULL;
4940
58.4k
        viewport->DrawDataP.Valid = false;
4941
58.4k
    }
4942
4943
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4944
58.4k
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4945
90
        KeepAliveID(g.DragDropPayload.SourceId);
4946
4947
    // Update HoveredId data
4948
58.4k
    if (!g.HoveredIdPreviousFrame)
4949
58.4k
        g.HoveredIdTimer = 0.0f;
4950
58.4k
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4951
58.4k
        g.HoveredIdNotActiveTimer = 0.0f;
4952
58.4k
    if (g.HoveredId)
4953
9
        g.HoveredIdTimer += g.IO.DeltaTime;
4954
58.4k
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4955
9
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4956
58.4k
    g.HoveredIdPreviousFrame = g.HoveredId;
4957
58.4k
    g.HoveredId = 0;
4958
58.4k
    g.HoveredIdAllowOverlap = false;
4959
58.4k
    g.HoveredIdIsDisabled = false;
4960
4961
    // Clear ActiveID if the item is not alive anymore.
4962
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4963
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4964
58.4k
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4965
0
    {
4966
0
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4967
0
        ClearActiveID();
4968
0
    }
4969
4970
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4971
58.4k
    if (g.ActiveId)
4972
92
        g.ActiveIdTimer += g.IO.DeltaTime;
4973
58.4k
    g.LastActiveIdTimer += g.IO.DeltaTime;
4974
58.4k
    g.ActiveIdPreviousFrame = g.ActiveId;
4975
58.4k
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4976
58.4k
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4977
58.4k
    g.ActiveIdIsAlive = 0;
4978
58.4k
    g.ActiveIdHasBeenEditedThisFrame = false;
4979
58.4k
    g.ActiveIdPreviousFrameIsAlive = false;
4980
58.4k
    g.ActiveIdIsJustActivated = false;
4981
58.4k
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4982
0
        g.TempInputId = 0;
4983
58.4k
    if (g.ActiveId == 0)
4984
58.3k
    {
4985
58.3k
        g.ActiveIdUsingNavDirMask = 0x00;
4986
58.3k
        g.ActiveIdUsingAllKeyboardKeys = false;
4987
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4988
        g.ActiveIdUsingNavInputMask = 0x00;
4989
#endif
4990
58.3k
    }
4991
4992
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4993
    if (g.ActiveId == 0)
4994
        g.ActiveIdUsingNavInputMask = 0;
4995
    else if (g.ActiveIdUsingNavInputMask != 0)
4996
    {
4997
        // If your custom widget code used:                 { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4998
        // Since IMGUI_VERSION_NUM >= 18804 it should be:   { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4999
        if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
5000
            SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
5001
        if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
5002
            IM_ASSERT(0); // Other values unsupported
5003
    }
5004
#endif
5005
5006
    // Record when we have been stationary as this state is preserved while over same item.
5007
    // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
5008
    // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
5009
58.4k
    if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
5010
0
        g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
5011
58.4k
    else if (g.HoverItemDelayId == 0)
5012
58.4k
        g.HoverItemUnlockedStationaryId = 0;
5013
58.4k
    if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
5014
0
        g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
5015
58.4k
    else if (g.HoveredWindow == NULL)
5016
58.4k
        g.HoverWindowUnlockedStationaryId = 0;
5017
5018
    // Update hover delay for IsItemHovered() with delays and tooltips
5019
58.4k
    g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
5020
58.4k
    if (g.HoverItemDelayId != 0)
5021
0
    {
5022
0
        g.HoverItemDelayTimer += g.IO.DeltaTime;
5023
0
        g.HoverItemDelayClearTimer = 0.0f;
5024
0
        g.HoverItemDelayId = 0;
5025
0
    }
5026
58.4k
    else if (g.HoverItemDelayTimer > 0.0f)
5027
0
    {
5028
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
5029
        // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
5030
0
        g.HoverItemDelayClearTimer += g.IO.DeltaTime;
5031
0
        if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
5032
0
            g.HoverItemDelayTimer = g.HoverItemDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
5033
0
    }
5034
5035
    // Drag and drop
5036
58.4k
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
5037
58.4k
    g.DragDropAcceptIdCurr = 0;
5038
58.4k
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
5039
58.4k
    g.DragDropWithinSource = false;
5040
58.4k
    g.DragDropWithinTarget = false;
5041
58.4k
    g.DragDropHoldJustPressedId = 0;
5042
5043
    // Close popups on focus lost (currently wip/opt-in)
5044
    //if (g.IO.AppFocusLost)
5045
    //    ClosePopupsExceptModals();
5046
5047
    // Update keyboard input state
5048
58.4k
    UpdateKeyboardInputs();
5049
5050
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
5051
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
5052
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
5053
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
5054
5055
    // Update gamepad/keyboard navigation
5056
58.4k
    NavUpdate();
5057
5058
    // Update mouse input state
5059
58.4k
    UpdateMouseInputs();
5060
5061
    // Undocking
5062
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
5063
58.4k
    DockContextNewFrameUpdateUndocking(&g);
5064
5065
    // Find hovered window
5066
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
5067
58.4k
    UpdateHoveredWindowAndCaptureFlags();
5068
5069
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
5070
58.4k
    UpdateMouseMovingWindowNewFrame();
5071
5072
    // Background darkening/whitening
5073
58.4k
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
5074
0
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
5075
58.4k
    else
5076
58.4k
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
5077
5078
58.4k
    g.MouseCursor = ImGuiMouseCursor_Arrow;
5079
58.4k
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
5080
5081
    // Platform IME data: reset for the frame
5082
58.4k
    g.PlatformImeDataPrev = g.PlatformImeData;
5083
58.4k
    g.PlatformImeData.WantVisible = false;
5084
5085
    // Mouse wheel scrolling, scale
5086
58.4k
    UpdateMouseWheel();
5087
5088
    // Mark all windows as not visible and compact unused memory.
5089
58.4k
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
5090
58.4k
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
5091
58.4k
    for (ImGuiWindow* window : g.Windows)
5092
175k
    {
5093
175k
        window->WasActive = window->Active;
5094
175k
        window->Active = false;
5095
175k
        window->WriteAccessed = false;
5096
175k
        window->BeginCountPreviousFrame = window->BeginCount;
5097
175k
        window->BeginCount = 0;
5098
5099
        // Garbage collect transient buffers of recently unused windows
5100
175k
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
5101
1
            GcCompactTransientWindowBuffers(window);
5102
175k
    }
5103
5104
    // Garbage collect transient buffers of recently unused tables
5105
58.4k
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
5106
0
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
5107
0
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
5108
58.4k
    for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
5109
0
        if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
5110
0
            TableGcCompactTransientBuffers(&table_temp_data);
5111
58.4k
    if (g.GcCompactAll)
5112
0
        GcCompactTransientMiscBuffers();
5113
58.4k
    g.GcCompactAll = false;
5114
5115
    // Closing the focused window restore focus to the first active root window in descending z-order
5116
58.4k
    if (g.NavWindow && !g.NavWindow->WasActive)
5117
0
        FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
5118
5119
    // No window should be open at the beginning of the frame.
5120
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
5121
58.4k
    g.CurrentWindowStack.resize(0);
5122
58.4k
    g.BeginPopupStack.resize(0);
5123
58.4k
    g.ItemFlagsStack.resize(0);
5124
58.4k
    g.ItemFlagsStack.push_back(ImGuiItemFlags_AutoClosePopups); // Default flags
5125
58.4k
    g.CurrentItemFlags = g.ItemFlagsStack.back();
5126
58.4k
    g.GroupStack.resize(0);
5127
5128
    // Docking
5129
58.4k
    DockContextNewFrameUpdateDocking(&g);
5130
5131
    // [DEBUG] Update debug features
5132
58.4k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5133
58.4k
    UpdateDebugToolItemPicker();
5134
58.4k
    UpdateDebugToolStackQueries();
5135
58.4k
    UpdateDebugToolFlashStyleColor();
5136
58.4k
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
5137
0
    {
5138
0
        g.DebugLocateId = 0;
5139
0
        g.DebugBreakInLocateId = false;
5140
0
    }
5141
58.4k
    if (g.DebugLogAutoDisableFrames > 0 && --g.DebugLogAutoDisableFrames == 0)
5142
0
    {
5143
0
        DebugLog("(Debug Log: Auto-disabled some ImGuiDebugLogFlags after 2 frames)\n");
5144
0
        g.DebugLogFlags &= ~g.DebugLogAutoDisableFlags;
5145
0
        g.DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
5146
0
    }
5147
58.4k
#endif
5148
5149
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
5150
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
5151
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
5152
58.4k
    g.WithinFrameScopeWithImplicitWindow = true;
5153
58.4k
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
5154
58.4k
    Begin("Debug##Default");
5155
58.4k
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
5156
5157
    // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
5158
    // allowing to validate correct Begin/End behavior in user code.
5159
58.4k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5160
58.4k
    if (g.IO.ConfigDebugBeginReturnValueLoop)
5161
0
        g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
5162
58.4k
    else
5163
58.4k
        g.DebugBeginReturnValueCullDepth = -1;
5164
58.4k
#endif
5165
5166
58.4k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
5167
58.4k
}
5168
5169
// FIXME: Add a more explicit sort order in the window structure.
5170
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5171
0
{
5172
0
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5173
0
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5174
0
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5175
0
        return d;
5176
0
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5177
0
        return d;
5178
0
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5179
0
}
5180
5181
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5182
175k
{
5183
175k
    out_sorted_windows->push_back(window);
5184
175k
    if (window->Active)
5185
68.7k
    {
5186
68.7k
        int count = window->DC.ChildWindows.Size;
5187
68.7k
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
5188
78.9k
        for (int i = 0; i < count; i++)
5189
10.2k
        {
5190
10.2k
            ImGuiWindow* child = window->DC.ChildWindows[i];
5191
10.2k
            if (child->Active)
5192
10.2k
                AddWindowToSortBuffer(out_sorted_windows, child);
5193
10.2k
        }
5194
68.7k
    }
5195
175k
}
5196
5197
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5198
58.5k
{
5199
58.5k
    ImGuiContext& g = *GImGui;
5200
58.5k
    ImGuiViewportP* viewport = window->Viewport;
5201
58.5k
    IM_ASSERT(viewport != NULL);
5202
58.5k
    g.IO.MetricsRenderWindows++;
5203
58.5k
    if (window->DrawList->_Splitter._Count > 1)
5204
0
        window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5205
58.5k
    ImGui::AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5206
58.5k
    for (ImGuiWindow* child : window->DC.ChildWindows)
5207
10.2k
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5208
125
            AddWindowToDrawData(child, layer);
5209
58.5k
}
5210
5211
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5212
58.4k
{
5213
58.4k
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5214
58.4k
}
5215
5216
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5217
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5218
58.4k
{
5219
58.4k
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5220
58.4k
}
5221
5222
static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5223
58.4k
{
5224
58.4k
    int n = builder->Layers[0]->Size;
5225
58.4k
    int full_size = n;
5226
116k
    for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5227
58.4k
        full_size += builder->Layers[i]->Size;
5228
58.4k
    builder->Layers[0]->resize(full_size);
5229
116k
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5230
58.4k
    {
5231
58.4k
        ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5232
58.4k
        if (layer->empty())
5233
58.4k
            continue;
5234
0
        memcpy(builder->Layers[0]->Data + n, layer->Data, layer->Size * sizeof(ImDrawList*));
5235
0
        n += layer->Size;
5236
0
        layer->resize(0);
5237
0
    }
5238
58.4k
}
5239
5240
static void InitViewportDrawData(ImGuiViewportP* viewport)
5241
58.4k
{
5242
58.4k
    ImGuiIO& io = ImGui::GetIO();
5243
58.4k
    ImDrawData* draw_data = &viewport->DrawDataP;
5244
5245
58.4k
    viewport->DrawData = draw_data; // Make publicly accessible
5246
58.4k
    viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5247
58.4k
    viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5248
58.4k
    viewport->DrawDataBuilder.Layers[0]->resize(0);
5249
58.4k
    viewport->DrawDataBuilder.Layers[1]->resize(0);
5250
5251
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5252
    // and to allow applications/backends to easily skip rendering.
5253
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5254
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5255
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5256
58.4k
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
5257
5258
58.4k
    draw_data->Valid = true;
5259
58.4k
    draw_data->CmdListsCount = 0;
5260
58.4k
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5261
58.4k
    draw_data->DisplayPos = viewport->Pos;
5262
58.4k
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5263
58.4k
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
5264
58.4k
    draw_data->OwnerViewport = viewport;
5265
58.4k
}
5266
5267
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5268
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5269
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5270
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5271
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5272
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5273
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5274
254k
{
5275
254k
    ImGuiWindow* window = GetCurrentWindow();
5276
254k
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5277
254k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5278
254k
}
5279
5280
void ImGui::PopClipRect()
5281
127k
{
5282
127k
    ImGuiWindow* window = GetCurrentWindow();
5283
127k
    window->DrawList->PopClipRect();
5284
127k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5285
127k
}
5286
5287
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5288
0
{
5289
0
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5290
0
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
5291
0
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
5292
0
    return window;
5293
0
}
5294
5295
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5296
0
{
5297
0
    if ((col & IM_COL32_A_MASK) == 0)
5298
0
        return;
5299
5300
0
    ImGuiViewportP* viewport = window->Viewport;
5301
0
    ImRect viewport_rect = viewport->GetMainRect();
5302
5303
    // Draw behind window by moving the draw command at the FRONT of the draw list
5304
0
    {
5305
        // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5306
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5307
0
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5308
0
        draw_list->ChannelsMerge();
5309
0
        if (draw_list->CmdBuffer.Size == 0)
5310
0
            draw_list->AddDrawCmd();
5311
0
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
5312
0
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5313
0
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
5314
0
        IM_ASSERT(cmd.ElemCount == 6);
5315
0
        draw_list->CmdBuffer.pop_back();
5316
0
        draw_list->CmdBuffer.push_front(cmd);
5317
0
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5318
0
        draw_list->PopClipRect();
5319
0
    }
5320
5321
    // Draw over sibling docking nodes in a same docking tree
5322
0
    if (window->RootWindow->DockIsActive)
5323
0
    {
5324
0
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5325
0
        draw_list->ChannelsMerge();
5326
0
        if (draw_list->CmdBuffer.Size == 0)
5327
0
            draw_list->AddDrawCmd();
5328
0
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5329
0
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5330
0
        draw_list->PopClipRect();
5331
0
    }
5332
0
}
5333
5334
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5335
0
{
5336
0
    ImGuiContext& g = *GImGui;
5337
0
    ImGuiWindow* bottom_most_visible_window = parent_window;
5338
0
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5339
0
    {
5340
0
        ImGuiWindow* window = g.Windows[i];
5341
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
5342
0
            continue;
5343
0
        if (!IsWindowWithinBeginStackOf(window, parent_window))
5344
0
            break;
5345
0
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5346
0
            bottom_most_visible_window = window;
5347
0
    }
5348
0
    return bottom_most_visible_window;
5349
0
}
5350
5351
// Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage.
5352
// We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds().
5353
static void ImGui::RenderDimmedBackgrounds()
5354
58.4k
{
5355
58.4k
    ImGuiContext& g = *GImGui;
5356
58.4k
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5357
58.4k
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5358
58.4k
        return;
5359
0
    const bool dim_bg_for_modal = (modal_window != NULL);
5360
0
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5361
0
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
5362
0
        return;
5363
5364
0
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5365
0
    if (dim_bg_for_modal)
5366
0
    {
5367
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5368
0
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5369
0
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(modal_window->DC.ModalDimBgColor, g.DimBgRatio));
5370
0
        viewports_already_dimmed[0] = modal_window->Viewport;
5371
0
    }
5372
0
    else if (dim_bg_for_window_list)
5373
0
    {
5374
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5375
0
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5376
0
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5377
0
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5378
0
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5379
0
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5380
5381
        // Draw border around CTRL+Tab target window
5382
0
        ImGuiWindow* window = g.NavWindowingTargetAnim;
5383
0
        ImGuiViewport* viewport = window->Viewport;
5384
0
        float distance = g.FontSize;
5385
0
        ImRect bb = window->Rect();
5386
0
        bb.Expand(distance);
5387
0
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5388
0
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5389
0
        window->DrawList->ChannelsMerge();
5390
0
        if (window->DrawList->CmdBuffer.Size == 0)
5391
0
            window->DrawList->AddDrawCmd();
5392
0
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5393
0
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5394
0
        window->DrawList->PopClipRect();
5395
0
    }
5396
5397
    // Draw dimming background on _other_ viewports than the ones our windows are in
5398
0
    for (ImGuiViewportP* viewport : g.Viewports)
5399
0
    {
5400
0
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5401
0
            continue;
5402
0
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5403
0
            continue;
5404
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5405
0
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5406
0
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5407
0
    }
5408
0
}
5409
5410
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5411
void ImGui::EndFrame()
5412
116k
{
5413
116k
    ImGuiContext& g = *GImGui;
5414
116k
    IM_ASSERT(g.Initialized);
5415
5416
    // Don't process EndFrame() multiple times.
5417
116k
    if (g.FrameCountEnded == g.FrameCount)
5418
58.4k
        return;
5419
58.4k
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5420
5421
58.4k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5422
5423
58.4k
    ErrorCheckEndFrameSanityChecks();
5424
5425
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5426
58.4k
    ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5427
58.4k
    if (g.IO.PlatformSetImeDataFn != NULL && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5428
0
    {
5429
0
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5430
0
        IMGUI_DEBUG_LOG_IO("[io] Calling io.PlatformSetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5431
0
        if (viewport == NULL)
5432
0
            viewport = GetMainViewport();
5433
0
        g.IO.PlatformSetImeDataFn(&g, viewport, ime_data);
5434
0
    }
5435
5436
    // Hide implicit/fallback "Debug" window if it hasn't been used
5437
58.4k
    g.WithinFrameScopeWithImplicitWindow = false;
5438
58.4k
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5439
58.4k
        g.CurrentWindow->Active = false;
5440
58.4k
    End();
5441
5442
    // Update navigation: CTRL+Tab, wrap-around requests
5443
58.4k
    NavEndFrame();
5444
5445
    // Update docking
5446
58.4k
    DockContextEndFrame(&g);
5447
5448
58.4k
    SetCurrentViewport(NULL, NULL);
5449
5450
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5451
58.4k
    if (g.DragDropActive)
5452
92
    {
5453
92
        bool is_delivered = g.DragDropPayload.Delivery;
5454
92
        bool is_elapsed = (g.DragDropSourceFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_PayloadAutoExpire) || g.DragDropMouseButton == -1 || !IsMouseDown(g.DragDropMouseButton));
5455
92
        if (is_delivered || is_elapsed)
5456
1
            ClearDragDrop();
5457
92
    }
5458
5459
    // Drag and Drop: Fallback for missing source tooltip. This is not ideal but better than nothing.
5460
    // If you want to handle source item disappearing: instead of submitting your description tooltip
5461
    // in the BeginDragDropSource() block of the dragged item, you can submit them from a safe single spot
5462
    // (e.g. end of your item loop, or before EndFrame) by reading payload data.
5463
    // In the typical case, the contents of drag tooltip should be possible to infer solely from payload data.
5464
58.4k
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5465
0
    {
5466
0
        g.DragDropWithinSource = true;
5467
0
        SetTooltip("...");
5468
0
        g.DragDropWithinSource = false;
5469
0
    }
5470
5471
    // End frame
5472
58.4k
    g.WithinFrameScope = false;
5473
58.4k
    g.FrameCountEnded = g.FrameCount;
5474
5475
    // Initiate moving window + handle left-click and right-click focus
5476
58.4k
    UpdateMouseMovingWindowEndFrame();
5477
5478
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5479
58.4k
    UpdateViewportsEndFrame();
5480
5481
    // Sort the window list so that all child windows are after their parent
5482
    // We cannot do that on FocusWindow() because children may not exist yet
5483
58.4k
    g.WindowsTempSortBuffer.resize(0);
5484
58.4k
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5485
58.4k
    for (ImGuiWindow* window : g.Windows)
5486
175k
    {
5487
175k
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5488
10.2k
            continue;
5489
165k
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5490
165k
    }
5491
5492
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5493
58.4k
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5494
58.4k
    g.Windows.swap(g.WindowsTempSortBuffer);
5495
58.4k
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5496
5497
    // Unlock font atlas
5498
58.4k
    g.IO.Fonts->Locked = false;
5499
5500
    // Clear Input data for next frame
5501
58.4k
    g.IO.MousePosPrev = g.IO.MousePos;
5502
58.4k
    g.IO.AppFocusLost = false;
5503
58.4k
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5504
58.4k
    g.IO.InputQueueCharacters.resize(0);
5505
5506
58.4k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5507
58.4k
}
5508
5509
// Prepare the data for rendering so you can call GetDrawData()
5510
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5511
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5512
void ImGui::Render()
5513
58.4k
{
5514
58.4k
    ImGuiContext& g = *GImGui;
5515
58.4k
    IM_ASSERT(g.Initialized);
5516
5517
58.4k
    if (g.FrameCountEnded != g.FrameCount)
5518
58.4k
        EndFrame();
5519
58.4k
    if (g.FrameCountRendered == g.FrameCount)
5520
0
        return;
5521
58.4k
    g.FrameCountRendered = g.FrameCount;
5522
5523
58.4k
    g.IO.MetricsRenderWindows = 0;
5524
58.4k
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5525
5526
    // Add background ImDrawList (for each active viewport)
5527
58.4k
    for (ImGuiViewportP* viewport : g.Viewports)
5528
58.4k
    {
5529
58.4k
        InitViewportDrawData(viewport);
5530
58.4k
        if (viewport->BgFgDrawLists[0] != NULL)
5531
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5532
58.4k
    }
5533
5534
    // Draw modal/window whitening backgrounds
5535
58.4k
    RenderDimmedBackgrounds();
5536
5537
    // Add ImDrawList to render
5538
58.4k
    ImGuiWindow* windows_to_render_top_most[2];
5539
58.4k
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5540
58.4k
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5541
58.4k
    for (ImGuiWindow* window : g.Windows)
5542
175k
    {
5543
175k
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5544
175k
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5545
58.4k
            AddRootWindowToDrawData(window);
5546
175k
    }
5547
175k
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5548
116k
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5549
0
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5550
5551
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5552
58.4k
    if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
5553
0
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5554
5555
    // Setup ImDrawData structures for end-user
5556
58.4k
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5557
58.4k
    for (ImGuiViewportP* viewport : g.Viewports)
5558
58.4k
    {
5559
58.4k
        FlattenDrawDataIntoSingleLayer(&viewport->DrawDataBuilder);
5560
5561
        // Add foreground ImDrawList (for each active viewport)
5562
58.4k
        if (viewport->BgFgDrawLists[1] != NULL)
5563
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5564
5565
        // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
5566
58.4k
        ImDrawData* draw_data = &viewport->DrawDataP;
5567
58.4k
        IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
5568
58.4k
        for (ImDrawList* draw_list : draw_data->CmdLists)
5569
58.5k
            draw_list->_PopUnusedDrawCmd();
5570
5571
58.4k
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5572
58.4k
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5573
58.4k
    }
5574
5575
58.4k
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5576
58.4k
}
5577
5578
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5579
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5580
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5581
116k
{
5582
116k
    ImGuiContext& g = *GImGui;
5583
5584
116k
    const char* text_display_end;
5585
116k
    if (hide_text_after_double_hash)
5586
116k
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5587
0
    else
5588
0
        text_display_end = text_end;
5589
5590
116k
    ImFont* font = g.Font;
5591
116k
    const float font_size = g.FontSize;
5592
116k
    if (text == text_display_end)
5593
0
        return ImVec2(0.0f, font_size);
5594
116k
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5595
5596
    // Round
5597
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5598
    // FIXME: Investigate using ceilf or e.g.
5599
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5600
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5601
116k
    text_size.x = IM_TRUNC(text_size.x + 0.99999f);
5602
5603
116k
    return text_size;
5604
116k
}
5605
5606
// Find window given position, search front-to-back
5607
// - Typically write output back to g.HoveredWindow and g.HoveredWindowUnderMovingWindow.
5608
// - FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5609
//   with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5610
//   called, aka before the next Begin(). Moving window isn't affected.
5611
// - The 'find_first_and_in_any_viewport = true' mode is only used by TestEngine. It is simpler to maintain here.
5612
void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window)
5613
58.4k
{
5614
58.4k
    ImGuiContext& g = *GImGui;
5615
58.4k
    ImGuiWindow* hovered_window = NULL;
5616
58.4k
    ImGuiWindow* hovered_window_under_moving_window = NULL;
5617
5618
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5619
58.4k
    ImGuiViewportP* backup_moving_window_viewport = NULL;
5620
58.4k
    if (find_first_and_in_any_viewport == false && g.MovingWindow)
5621
92
    {
5622
92
        backup_moving_window_viewport = g.MovingWindow->Viewport;
5623
92
        g.MovingWindow->Viewport = g.MouseViewport;
5624
92
        if (!(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5625
92
            hovered_window = g.MovingWindow;
5626
92
    }
5627
5628
58.4k
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5629
58.4k
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5630
233k
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5631
175k
    {
5632
175k
        ImGuiWindow* window = g.Windows[i];
5633
175k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5634
175k
        if (!window->Active || window->Hidden)
5635
116k
            continue;
5636
58.5k
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5637
0
            continue;
5638
58.5k
        IM_ASSERT(window->Viewport);
5639
58.5k
        if (window->Viewport != g.MouseViewport)
5640
0
            continue;
5641
5642
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5643
58.5k
        ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
5644
58.5k
        if (!window->OuterRectClipped.ContainsWithPad(pos, hit_padding))
5645
58.5k
            continue;
5646
5647
        // Support for one rectangular hole in any given window
5648
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5649
61
        if (window->HitTestHoleSize.x != 0)
5650
0
        {
5651
0
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5652
0
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5653
0
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(pos))
5654
0
                continue;
5655
0
        }
5656
5657
61
        if (find_first_and_in_any_viewport)
5658
0
        {
5659
0
            hovered_window = window;
5660
0
            break;
5661
0
        }
5662
61
        else
5663
61
        {
5664
61
            if (hovered_window == NULL)
5665
12
                hovered_window = window;
5666
61
            IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5667
61
            if (hovered_window_under_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5668
12
                hovered_window_under_moving_window = window;
5669
61
            if (hovered_window && hovered_window_under_moving_window)
5670
12
                break;
5671
61
        }
5672
61
    }
5673
5674
58.4k
    *out_hovered_window = hovered_window;
5675
58.4k
    if (out_hovered_window_under_moving_window != NULL)
5676
58.4k
        *out_hovered_window_under_moving_window = hovered_window_under_moving_window;
5677
58.4k
    if (find_first_and_in_any_viewport == false && g.MovingWindow)
5678
92
        g.MovingWindow->Viewport = backup_moving_window_viewport;
5679
58.4k
}
5680
5681
bool ImGui::IsItemActive()
5682
116k
{
5683
116k
    ImGuiContext& g = *GImGui;
5684
116k
    if (g.ActiveId)
5685
154
        return g.ActiveId == g.LastItemData.ID;
5686
116k
    return false;
5687
116k
}
5688
5689
bool ImGui::IsItemActivated()
5690
0
{
5691
0
    ImGuiContext& g = *GImGui;
5692
0
    if (g.ActiveId)
5693
0
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5694
0
            return true;
5695
0
    return false;
5696
0
}
5697
5698
bool ImGui::IsItemDeactivated()
5699
0
{
5700
0
    ImGuiContext& g = *GImGui;
5701
0
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5702
0
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5703
0
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5704
0
}
5705
5706
bool ImGui::IsItemDeactivatedAfterEdit()
5707
0
{
5708
0
    ImGuiContext& g = *GImGui;
5709
0
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5710
0
}
5711
5712
// == GetItemID() == GetFocusID()
5713
bool ImGui::IsItemFocused()
5714
0
{
5715
0
    ImGuiContext& g = *GImGui;
5716
0
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5717
0
        return false;
5718
5719
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5720
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5721
0
    ImGuiWindow* window = g.CurrentWindow;
5722
0
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5723
0
        return false;
5724
5725
0
    return true;
5726
0
}
5727
5728
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5729
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5730
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5731
0
{
5732
0
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5733
0
}
5734
5735
bool ImGui::IsItemToggledOpen()
5736
0
{
5737
0
    ImGuiContext& g = *GImGui;
5738
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5739
0
}
5740
5741
// Call after a Selectable() or TreeNode() involved in multi-selection.
5742
// Useful if you need the per-item information before reaching EndMultiSelect(), e.g. for rendering purpose.
5743
// This is only meant to be called inside a BeginMultiSelect()/EndMultiSelect() block.
5744
// (Outside of multi-select, it would be misleading/ambiguous to report this signal, as widgets
5745
// return e.g. a pressed event and user code is in charge of altering selection in ways we cannot predict.)
5746
bool ImGui::IsItemToggledSelection()
5747
0
{
5748
0
    ImGuiContext& g = *GImGui;
5749
0
    IM_ASSERT(g.CurrentMultiSelect != NULL); // Can only be used inside a BeginMultiSelect()/EndMultiSelect()
5750
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5751
0
}
5752
5753
// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
5754
// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
5755
// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
5756
bool ImGui::IsAnyItemHovered()
5757
0
{
5758
0
    ImGuiContext& g = *GImGui;
5759
0
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5760
0
}
5761
5762
bool ImGui::IsAnyItemActive()
5763
0
{
5764
0
    ImGuiContext& g = *GImGui;
5765
0
    return g.ActiveId != 0;
5766
0
}
5767
5768
bool ImGui::IsAnyItemFocused()
5769
0
{
5770
0
    ImGuiContext& g = *GImGui;
5771
0
    return g.NavId != 0 && !g.NavDisableHighlight;
5772
0
}
5773
5774
bool ImGui::IsItemVisible()
5775
0
{
5776
0
    ImGuiContext& g = *GImGui;
5777
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5778
0
}
5779
5780
bool ImGui::IsItemEdited()
5781
0
{
5782
0
    ImGuiContext& g = *GImGui;
5783
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5784
0
}
5785
5786
// Allow next item to be overlapped by subsequent items.
5787
// This works by requiring HoveredId to match for two subsequent frames,
5788
// so if a following items overwrite it our interactions will naturally be disabled.
5789
void ImGui::SetNextItemAllowOverlap()
5790
0
{
5791
0
    ImGuiContext& g = *GImGui;
5792
0
    g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
5793
0
}
5794
5795
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5796
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5797
// FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
5798
void ImGui::SetItemAllowOverlap()
5799
{
5800
    ImGuiContext& g = *GImGui;
5801
    ImGuiID id = g.LastItemData.ID;
5802
    if (g.HoveredId == id)
5803
        g.HoveredIdAllowOverlap = true;
5804
    if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
5805
        g.ActiveIdAllowOverlap = true;
5806
}
5807
#endif
5808
5809
// This is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations.
5810
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version if needed?
5811
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5812
92
{
5813
92
    ImGuiContext& g = *GImGui;
5814
92
    IM_ASSERT(g.ActiveId != 0);
5815
92
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5816
92
    g.ActiveIdUsingAllKeyboardKeys = true;
5817
92
    NavMoveRequestCancel();
5818
92
}
5819
5820
ImGuiID ImGui::GetItemID()
5821
0
{
5822
0
    ImGuiContext& g = *GImGui;
5823
0
    return g.LastItemData.ID;
5824
0
}
5825
5826
ImVec2 ImGui::GetItemRectMin()
5827
0
{
5828
0
    ImGuiContext& g = *GImGui;
5829
0
    return g.LastItemData.Rect.Min;
5830
0
}
5831
5832
ImVec2 ImGui::GetItemRectMax()
5833
0
{
5834
0
    ImGuiContext& g = *GImGui;
5835
0
    return g.LastItemData.Rect.Max;
5836
0
}
5837
5838
ImVec2 ImGui::GetItemRectSize()
5839
0
{
5840
0
    ImGuiContext& g = *GImGui;
5841
0
    return g.LastItemData.Rect.GetSize();
5842
0
}
5843
5844
// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
5845
// ImGuiChildFlags_Border is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details!
5846
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5847
10.2k
{
5848
10.2k
    ImGuiID id = GetCurrentWindow()->GetID(str_id);
5849
10.2k
    return BeginChildEx(str_id, id, size_arg, child_flags, window_flags);
5850
10.2k
}
5851
5852
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5853
0
{
5854
0
    return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
5855
0
}
5856
5857
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5858
10.2k
{
5859
10.2k
    ImGuiContext& g = *GImGui;
5860
10.2k
    ImGuiWindow* parent_window = g.CurrentWindow;
5861
10.2k
    IM_ASSERT(id != 0);
5862
5863
    // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
5864
10.2k
    const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle | ImGuiChildFlags_NavFlattened;
5865
10.2k
    IM_UNUSED(ImGuiChildFlags_SupportedMask_);
5866
10.2k
    IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
5867
10.2k
    IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!");
5868
10.2k
    if (child_flags & ImGuiChildFlags_AlwaysAutoResize)
5869
0
    {
5870
0
        IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5871
0
        IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5872
0
    }
5873
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5874
    if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding)
5875
        child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding;
5876
    if (window_flags & ImGuiWindowFlags_NavFlattened)
5877
        child_flags |= ImGuiChildFlags_NavFlattened;
5878
#endif
5879
10.2k
    if (child_flags & ImGuiChildFlags_AutoResizeX)
5880
0
        child_flags &= ~ImGuiChildFlags_ResizeX;
5881
10.2k
    if (child_flags & ImGuiChildFlags_AutoResizeY)
5882
0
        child_flags &= ~ImGuiChildFlags_ResizeY;
5883
5884
    // Set window flags
5885
10.2k
    window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking;
5886
10.2k
    window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
5887
10.2k
    if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize))
5888
0
        window_flags |= ImGuiWindowFlags_AlwaysAutoResize;
5889
10.2k
    if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
5890
10.2k
        window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
5891
5892
    // Special framed style
5893
10.2k
    if (child_flags & ImGuiChildFlags_FrameStyle)
5894
0
    {
5895
0
        PushStyleColor(ImGuiCol_ChildBg, g.Style.Colors[ImGuiCol_FrameBg]);
5896
0
        PushStyleVar(ImGuiStyleVar_ChildRounding, g.Style.FrameRounding);
5897
0
        PushStyleVar(ImGuiStyleVar_ChildBorderSize, g.Style.FrameBorderSize);
5898
0
        PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.FramePadding);
5899
0
        child_flags |= ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding;
5900
0
        window_flags |= ImGuiWindowFlags_NoMove;
5901
0
    }
5902
5903
    // Forward child flags
5904
10.2k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags;
5905
10.2k
    g.NextWindowData.ChildFlags = child_flags;
5906
5907
    // Forward size
5908
    // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
5909
    // (the alternative would to store conditional flags per axis, which is possible but more code)
5910
10.2k
    const ImVec2 size_avail = GetContentRegionAvail();
5911
10.2k
    const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
5912
10.2k
    const ImVec2 size = CalcItemSize(size_arg, size_default.x, size_default.y);
5913
10.2k
    SetNextWindowSize(size);
5914
5915
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5916
    // FIXME: 2023/11/14: commented out shorted version. We had an issue with multiple ### in child window path names, which the trailing hash helped workaround.
5917
    // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it.
5918
10.2k
    const char* temp_window_name;
5919
    /*if (name && parent_window->IDStack.back() == parent_window->ID)
5920
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
5921
    else*/
5922
10.2k
    if (name)
5923
10.2k
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5924
0
    else
5925
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5926
5927
    // Set style
5928
10.2k
    const float backup_border_size = g.Style.ChildBorderSize;
5929
10.2k
    if ((child_flags & ImGuiChildFlags_Border) == 0)
5930
4.61k
        g.Style.ChildBorderSize = 0.0f;
5931
5932
    // Begin into window
5933
10.2k
    const bool ret = Begin(temp_window_name, NULL, window_flags);
5934
5935
    // Restore style
5936
10.2k
    g.Style.ChildBorderSize = backup_border_size;
5937
10.2k
    if (child_flags & ImGuiChildFlags_FrameStyle)
5938
0
    {
5939
0
        PopStyleVar(3);
5940
0
        PopStyleColor();
5941
0
    }
5942
5943
10.2k
    ImGuiWindow* child_window = g.CurrentWindow;
5944
10.2k
    child_window->ChildId = id;
5945
5946
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5947
    // While this is not really documented/defined, it seems that the expected thing to do.
5948
10.2k
    if (child_window->BeginCount == 1)
5949
10.2k
        parent_window->DC.CursorPos = child_window->Pos;
5950
5951
    // Process navigation-in immediately so NavInit can run on first frame
5952
    // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
5953
10.2k
    const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id);
5954
10.2k
    if (g.ActiveId == temp_id_for_activation)
5955
0
        ClearActiveID();
5956
10.2k
    if (g.NavActivateId == id && !(child_flags & ImGuiChildFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
5957
12
    {
5958
12
        FocusWindow(child_window);
5959
12
        NavInitWindow(child_window, false);
5960
12
        SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5961
12
        g.ActiveIdSource = g.NavInputSource;
5962
12
    }
5963
10.2k
    return ret;
5964
10.2k
}
5965
5966
void ImGui::EndChild()
5967
10.2k
{
5968
10.2k
    ImGuiContext& g = *GImGui;
5969
10.2k
    ImGuiWindow* child_window = g.CurrentWindow;
5970
5971
10.2k
    IM_ASSERT(g.WithinEndChild == false);
5972
10.2k
    IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5973
5974
10.2k
    g.WithinEndChild = true;
5975
10.2k
    ImVec2 child_size = child_window->Size;
5976
10.2k
    End();
5977
10.2k
    if (child_window->BeginCount == 1)
5978
10.2k
    {
5979
10.2k
        ImGuiWindow* parent_window = g.CurrentWindow;
5980
10.2k
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
5981
10.2k
        ItemSize(child_size);
5982
10.2k
        const bool nav_flattened = (child_window->ChildFlags & ImGuiChildFlags_NavFlattened) != 0;
5983
10.2k
        if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !nav_flattened)
5984
8.77k
        {
5985
8.77k
            ItemAdd(bb, child_window->ChildId);
5986
8.77k
            RenderNavHighlight(bb, child_window->ChildId);
5987
5988
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5989
8.77k
            if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
5990
4.65k
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_Compact);
5991
8.77k
        }
5992
1.45k
        else
5993
1.45k
        {
5994
            // Not navigable into
5995
            // - This is a bit of a fringe use case, mostly useful for undecorated, non-scrolling contents childs, or empty childs.
5996
            // - We could later decide to not apply this path if ImGuiChildFlags_FrameStyle or ImGuiChildFlags_Borders is set.
5997
1.45k
            ItemAdd(bb, child_window->ChildId, NULL, ImGuiItemFlags_NoNav);
5998
5999
            // But when flattened we directly reach items, adjust active layer mask accordingly
6000
1.45k
            if (nav_flattened)
6001
0
                parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
6002
1.45k
        }
6003
10.2k
        if (g.HoveredWindow == child_window)
6004
1
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
6005
10.2k
    }
6006
10.2k
    g.WithinEndChild = false;
6007
10.2k
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
6008
10.2k
}
6009
6010
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
6011
6
{
6012
6
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
6013
6
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
6014
6
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
6015
6
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
6016
6
}
6017
6018
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
6019
127k
{
6020
127k
    ImGuiContext& g = *GImGui;
6021
127k
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
6022
127k
}
6023
6024
ImGuiWindow* ImGui::FindWindowByName(const char* name)
6025
127k
{
6026
127k
    ImGuiID id = ImHashStr(name);
6027
127k
    return FindWindowByID(id);
6028
127k
}
6029
6030
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6031
0
{
6032
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
6033
0
    window->ViewportPos = main_viewport->Pos;
6034
0
    if (settings->ViewportId)
6035
0
    {
6036
0
        window->ViewportId = settings->ViewportId;
6037
0
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
6038
0
    }
6039
0
    window->Pos = ImTrunc(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
6040
0
    if (settings->Size.x > 0 && settings->Size.y > 0)
6041
0
        window->Size = window->SizeFull = ImTrunc(ImVec2(settings->Size.x, settings->Size.y));
6042
0
    window->Collapsed = settings->Collapsed;
6043
0
    window->DockId = settings->DockId;
6044
0
    window->DockOrder = settings->DockOrder;
6045
0
}
6046
6047
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
6048
127k
{
6049
127k
    ImGuiContext& g = *GImGui;
6050
6051
127k
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
6052
127k
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
6053
127k
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
6054
2
    {
6055
2
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
6056
2
        g.WindowsFocusOrder.push_back(window);
6057
2
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
6058
2
    }
6059
127k
    else if (!just_created && child_flag_changed && new_is_explicit_child)
6060
0
    {
6061
0
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
6062
0
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
6063
0
            g.WindowsFocusOrder[n]->FocusOrder--;
6064
0
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
6065
0
        window->FocusOrder = -1;
6066
0
    }
6067
127k
    window->IsExplicitChild = new_is_explicit_child;
6068
127k
}
6069
6070
static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6071
3
{
6072
    // Initial window state with e.g. default/arbitrary window position
6073
    // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
6074
3
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
6075
3
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
6076
3
    window->Size = window->SizeFull = ImVec2(0, 0);
6077
3
    window->ViewportPos = main_viewport->Pos;
6078
3
    window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
6079
6080
3
    if (settings != NULL)
6081
0
    {
6082
0
        SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
6083
0
        ApplyWindowSettings(window, settings);
6084
0
    }
6085
3
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
6086
6087
3
    if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
6088
0
    {
6089
0
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
6090
0
        window->AutoFitOnlyGrows = false;
6091
0
    }
6092
3
    else
6093
3
    {
6094
3
        if (window->Size.x <= 0.0f)
6095
3
            window->AutoFitFramesX = 2;
6096
3
        if (window->Size.y <= 0.0f)
6097
3
            window->AutoFitFramesY = 2;
6098
3
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
6099
3
    }
6100
3
}
6101
6102
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
6103
3
{
6104
    // Create window the first time
6105
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
6106
3
    ImGuiContext& g = *GImGui;
6107
3
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
6108
3
    window->Flags = flags;
6109
3
    g.WindowsById.SetVoidPtr(window->ID, window);
6110
6111
3
    ImGuiWindowSettings* settings = NULL;
6112
3
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
6113
2
        if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
6114
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
6115
6116
3
    InitOrLoadWindowSettings(window, settings);
6117
6118
3
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
6119
0
        g.Windows.push_front(window); // Quite slow but rare and only once
6120
3
    else
6121
3
        g.Windows.push_back(window);
6122
6123
3
    return window;
6124
3
}
6125
6126
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
6127
0
{
6128
0
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
6129
0
}
6130
6131
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
6132
381k
{
6133
381k
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
6134
381k
}
6135
6136
static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
6137
381k
{
6138
    // We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
6139
    // FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller.
6140
    // Perhaps should tend further a neater test for this.
6141
381k
    ImGuiContext& g = *GImGui;
6142
381k
    ImVec2 size_min;
6143
381k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))
6144
30.7k
    {
6145
30.7k
        size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f;
6146
30.7k
        size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f;
6147
30.7k
    }
6148
350k
    else
6149
350k
    {
6150
350k
        size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f;
6151
350k
        size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : 4.0f;
6152
350k
    }
6153
6154
    // Reduce artifacts with very small windows
6155
381k
    ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
6156
381k
    size_min.y = ImMax(size_min.y, window_for_height->TitleBarHeight + window_for_height->MenuBarHeight + ImMax(0.0f, g.Style.WindowRounding - 1.0f));
6157
381k
    return size_min;
6158
381k
}
6159
6160
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
6161
254k
{
6162
254k
    ImGuiContext& g = *GImGui;
6163
254k
    ImVec2 new_size = size_desired;
6164
254k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
6165
0
    {
6166
        // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max.
6167
0
        ImRect cr = g.NextWindowData.SizeConstraintRect;
6168
0
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
6169
0
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
6170
0
        if (g.NextWindowData.SizeCallback)
6171
0
        {
6172
0
            ImGuiSizeCallbackData data;
6173
0
            data.UserData = g.NextWindowData.SizeCallbackUserData;
6174
0
            data.Pos = window->Pos;
6175
0
            data.CurrentSize = window->SizeFull;
6176
0
            data.DesiredSize = new_size;
6177
0
            g.NextWindowData.SizeCallback(&data);
6178
0
            new_size = data.DesiredSize;
6179
0
        }
6180
0
        new_size.x = IM_TRUNC(new_size.x);
6181
0
        new_size.y = IM_TRUNC(new_size.y);
6182
0
    }
6183
6184
    // Minimum size
6185
254k
    ImVec2 size_min = CalcWindowMinSize(window);
6186
254k
    return ImMax(new_size, size_min);
6187
254k
}
6188
6189
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
6190
127k
{
6191
127k
    bool preserve_old_content_sizes = false;
6192
127k
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
6193
48.2k
        preserve_old_content_sizes = true;
6194
78.9k
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6195
10.1k
        preserve_old_content_sizes = true;
6196
127k
    if (preserve_old_content_sizes)
6197
58.3k
    {
6198
58.3k
        *content_size_current = window->ContentSize;
6199
58.3k
        *content_size_ideal = window->ContentSizeIdeal;
6200
58.3k
        return;
6201
58.3k
    }
6202
6203
68.8k
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6204
68.8k
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6205
68.8k
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6206
68.8k
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6207
68.8k
}
6208
6209
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6210
127k
{
6211
127k
    ImGuiContext& g = *GImGui;
6212
127k
    ImGuiStyle& style = g.Style;
6213
127k
    const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6214
127k
    const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
6215
127k
    ImVec2 size_pad = window->WindowPadding * 2.0f;
6216
127k
    ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
6217
127k
    if (window->Flags & ImGuiWindowFlags_Tooltip)
6218
0
    {
6219
        // Tooltip always resize
6220
0
        return size_desired;
6221
0
    }
6222
127k
    else
6223
127k
    {
6224
        // Maximum window size is determined by the viewport size or monitor size
6225
127k
        ImVec2 size_min = CalcWindowMinSize(window);
6226
127k
        ImVec2 size_max = ImVec2(FLT_MAX, FLT_MAX);
6227
6228
        // Child windows are layed within their parent (unless they are also popups/menus) and thus have no restriction
6229
127k
        if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || (window->Flags & ImGuiWindowFlags_Popup) != 0)
6230
116k
        {
6231
116k
            if (!window->ViewportOwned)
6232
116k
                size_max = ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6233
116k
            const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
6234
116k
            if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
6235
0
                size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6236
116k
        }
6237
6238
127k
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, size_max));
6239
6240
        // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one axis may be auto-fit when calculating scrollbars,
6241
        // we may need to compute/store three variants of size_auto_fit, for x/y/xy.
6242
        // Here we implement a workaround for child windows only, but a full solution would apply to normal windows as well:
6243
127k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && !(window->ChildFlags & ImGuiChildFlags_ResizeY))
6244
0
            size_auto_fit.y = window->SizeFull.y;
6245
127k
        else if (!(window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->ChildFlags & ImGuiChildFlags_ResizeY))
6246
0
            size_auto_fit.x = window->SizeFull.x;
6247
6248
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6249
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6250
127k
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6251
127k
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
6252
127k
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
6253
127k
        if (will_have_scrollbar_x)
6254
10.2k
            size_auto_fit.y += style.ScrollbarSize;
6255
127k
        if (will_have_scrollbar_y)
6256
154
            size_auto_fit.x += style.ScrollbarSize;
6257
127k
        return size_auto_fit;
6258
127k
    }
6259
127k
}
6260
6261
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6262
0
{
6263
0
    ImVec2 size_contents_current;
6264
0
    ImVec2 size_contents_ideal;
6265
0
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
6266
0
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
6267
0
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6268
0
    return size_final;
6269
0
}
6270
6271
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6272
78.9k
{
6273
78.9k
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6274
0
        return ImGuiCol_PopupBg;
6275
78.9k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
6276
10.2k
        return ImGuiCol_ChildBg;
6277
68.7k
    return ImGuiCol_WindowBg;
6278
78.9k
}
6279
6280
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6281
0
{
6282
0
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
6283
0
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
6284
0
    ImVec2 size_expected = pos_max - pos_min;
6285
0
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
6286
0
    *out_pos = pos_min;
6287
0
    if (corner_norm.x == 0.0f)
6288
0
        out_pos->x -= (size_constrained.x - size_expected.x);
6289
0
    if (corner_norm.y == 0.0f)
6290
0
        out_pos->y -= (size_constrained.y - size_expected.y);
6291
0
    *out_size = size_constrained;
6292
0
}
6293
6294
// Data for resizing from resize grip / corner
6295
struct ImGuiResizeGripDef
6296
{
6297
    ImVec2  CornerPosN;
6298
    ImVec2  InnerDir;
6299
    int     AngleMin12, AngleMax12;
6300
};
6301
static const ImGuiResizeGripDef resize_grip_def[4] =
6302
{
6303
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
6304
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
6305
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
6306
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
6307
};
6308
6309
// Data for resizing from borders
6310
struct ImGuiResizeBorderDef
6311
{
6312
    ImVec2  InnerDir;               // Normal toward inside
6313
    ImVec2  SegmentN1, SegmentN2;   // End positions, normalized (0,0: upper left)
6314
    float   OuterAngle;             // Angle toward outside
6315
};
6316
static const ImGuiResizeBorderDef resize_border_def[4] =
6317
{
6318
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
6319
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
6320
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
6321
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
6322
};
6323
6324
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6325
40.9k
{
6326
40.9k
    ImRect rect = window->Rect();
6327
40.9k
    if (thickness == 0.0f)
6328
0
        rect.Max -= ImVec2(1, 1);
6329
40.9k
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
6330
30.6k
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
6331
20.4k
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
6332
10.2k
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
6333
0
    IM_ASSERT(0);
6334
0
    return ImRect();
6335
10.2k
}
6336
6337
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6338
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6339
0
{
6340
0
    IM_ASSERT(n >= 0 && n < 4);
6341
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6342
0
    id = ImHashStr("#RESIZE", 0, id);
6343
0
    id = ImHashData(&n, sizeof(int), id);
6344
0
    return id;
6345
0
}
6346
6347
// Borders (Left, Right, Up, Down)
6348
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6349
0
{
6350
0
    IM_ASSERT(dir >= 0 && dir < 4);
6351
0
    int n = (int)dir + 4;
6352
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6353
0
    id = ImHashStr("#RESIZE", 0, id);
6354
0
    id = ImHashData(&n, sizeof(int), id);
6355
0
    return id;
6356
0
}
6357
6358
// Handle resize for: Resize Grips, Borders, Gamepad
6359
// Return true when using auto-fit (double-click on resize grip)
6360
static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
6361
78.9k
{
6362
78.9k
    ImGuiContext& g = *GImGui;
6363
78.9k
    ImGuiWindowFlags flags = window->Flags;
6364
6365
78.9k
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6366
10.2k
        return false;
6367
68.7k
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6368
58.4k
        return false;
6369
6370
10.2k
    int ret_auto_fit_mask = 0x00;
6371
10.2k
    const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6372
10.2k
    const float grip_hover_inner_size = (resize_grip_count > 0) ? IM_TRUNC(grip_draw_size * 0.75f) : 0.0f;
6373
10.2k
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6374
6375
10.2k
    ImRect clamp_rect = visibility_rect;
6376
10.2k
    const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
6377
10.2k
    if (window_move_from_title_bar)
6378
0
        clamp_rect.Min.y -= window->TitleBarHeight;
6379
6380
10.2k
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
6381
10.2k
    ImVec2 size_target(FLT_MAX, FLT_MAX);
6382
6383
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
6384
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
6385
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
6386
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
6387
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
6388
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
6389
10.2k
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
6390
10.2k
    if (clip_with_viewport_rect)
6391
10.2k
        window->ClipRect = window->Viewport->GetMainRect();
6392
6393
    // Resize grips and borders are on layer 1
6394
10.2k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6395
6396
    // Manual resize grips
6397
10.2k
    PushID("#RESIZE");
6398
30.6k
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6399
20.4k
    {
6400
20.4k
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6401
20.4k
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
6402
6403
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6404
20.4k
        bool hovered, held;
6405
20.4k
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6406
20.4k
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
6407
20.4k
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
6408
20.4k
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
6409
20.4k
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
6410
20.4k
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6411
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6412
20.4k
        if (hovered || held)
6413
0
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6414
6415
20.4k
        if (held && g.IO.MouseDoubleClicked[0])
6416
0
        {
6417
            // Auto-fit when double-clicking
6418
0
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6419
0
            ret_auto_fit_mask = 0x03; // Both axises
6420
0
            ClearActiveID();
6421
0
        }
6422
20.4k
        else if (held)
6423
0
        {
6424
            // Resize from any of the four corners
6425
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6426
0
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? clamp_rect.Min.x : -FLT_MAX, (def.CornerPosN.y == 1.0f || (def.CornerPosN.y == 0.0f && window_move_from_title_bar)) ? clamp_rect.Min.y : -FLT_MAX);
6427
0
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? clamp_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? clamp_rect.Max.y : +FLT_MAX);
6428
0
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
6429
0
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
6430
0
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
6431
0
        }
6432
6433
        // Only lower-left grip is visible before hovering/activating
6434
20.4k
        if (resize_grip_n == 0 || held || hovered)
6435
10.2k
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6436
20.4k
    }
6437
6438
10.2k
    int resize_border_mask = 0x00;
6439
10.2k
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
6440
0
        resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
6441
10.2k
    else
6442
10.2k
        resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
6443
51.1k
    for (int border_n = 0; border_n < 4; border_n++)
6444
40.9k
    {
6445
40.9k
        if ((resize_border_mask & (1 << border_n)) == 0)
6446
0
            continue;
6447
40.9k
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6448
40.9k
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6449
6450
40.9k
        bool hovered, held;
6451
40.9k
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6452
40.9k
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
6453
40.9k
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
6454
40.9k
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6455
        //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6456
40.9k
        if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
6457
6
            hovered = false;
6458
40.9k
        if (hovered || held)
6459
0
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6460
40.9k
        if (held && g.IO.MouseDoubleClicked[0])
6461
0
        {
6462
            // Double-clicking bottom or right border auto-fit on this axis
6463
            // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one side may be auto-fit when calculating scrollbars.
6464
            // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
6465
0
            if (border_n == 1 || border_n == 3) // Right and bottom border
6466
0
            {
6467
0
                size_target[axis] = CalcWindowSizeAfterConstraint(window, size_auto_fit)[axis];
6468
0
                ret_auto_fit_mask |= (1 << axis);
6469
0
                hovered = held = false; // So border doesn't show highlighted at new position
6470
0
            }
6471
0
            ClearActiveID();
6472
0
        }
6473
40.9k
        else if (held)
6474
0
        {
6475
            // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
6476
            // Currently only using relative mode on resizable child windows, as the problem to solve is more likely noticeable for them, but could apply for all windows eventually.
6477
            // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
6478
0
            const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, g.WheelingWindow, false, true));
6479
0
            if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
6480
0
            {
6481
0
                g.WindowResizeBorderExpectedRect = border_rect;
6482
0
                g.WindowResizeRelativeMode = false;
6483
0
            }
6484
0
            if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(&g.WindowResizeBorderExpectedRect, &border_rect, sizeof(ImRect)) != 0)
6485
0
                g.WindowResizeRelativeMode = true;
6486
6487
0
            const ImVec2 border_curr = (window->Pos + ImMin(def.SegmentN1, def.SegmentN2) * window->Size);
6488
0
            const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
6489
0
            const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING; // Match ButtonBehavior() padding above.
6490
6491
            // Use absolute mode position
6492
0
            ImVec2 border_target = window->Pos;
6493
0
            border_target[axis] = border_target_abs_mode_for_axis;
6494
6495
            // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
6496
0
            bool ignore_resize = false;
6497
0
            if (g.WindowResizeRelativeMode)
6498
0
            {
6499
                //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
6500
0
                border_target[axis] = border_target_rel_mode_for_axis;
6501
0
                if (g.IO.MouseDelta[axis] == 0.0f || (g.IO.MouseDelta[axis] > 0.0f) == (border_target_rel_mode_for_axis > border_target_abs_mode_for_axis))
6502
0
                    ignore_resize = true;
6503
0
            }
6504
6505
            // Clamp, apply
6506
0
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? clamp_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down || (border_n == ImGuiDir_Up && window_move_from_title_bar) ? clamp_rect.Min.y : -FLT_MAX);
6507
0
            ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
6508
0
            border_target = ImClamp(border_target, clamp_min, clamp_max);
6509
0
            if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
6510
0
            {
6511
0
                ImGuiWindow* parent_window = window->ParentWindow;
6512
0
                ImGuiWindowFlags parent_flags = parent_window->Flags;
6513
0
                ImRect border_limit_rect = parent_window->InnerRect;
6514
0
                border_limit_rect.Expand(ImVec2(-ImMax(parent_window->WindowPadding.x, parent_window->WindowBorderSize), -ImMax(parent_window->WindowPadding.y, parent_window->WindowBorderSize)));
6515
0
                if ((axis == ImGuiAxis_X) && ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar)))
6516
0
                    border_target.x = ImClamp(border_target.x, border_limit_rect.Min.x, border_limit_rect.Max.x);
6517
0
                if ((axis == ImGuiAxis_Y) && (parent_flags & ImGuiWindowFlags_NoScrollbar))
6518
0
                    border_target.y = ImClamp(border_target.y, border_limit_rect.Min.y, border_limit_rect.Max.y);
6519
0
            }
6520
0
            if (!ignore_resize)
6521
0
                CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
6522
0
        }
6523
40.9k
        if (hovered)
6524
0
            *border_hovered = border_n;
6525
40.9k
        if (held)
6526
0
            *border_held = border_n;
6527
40.9k
    }
6528
10.2k
    PopID();
6529
6530
    // Restore nav layer
6531
10.2k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6532
6533
    // Navigation resize (keyboard/gamepad)
6534
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6535
    // Not even sure the callback works here.
6536
10.2k
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6537
0
    {
6538
0
        ImVec2 nav_resize_dir;
6539
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6540
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6541
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
6542
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6543
0
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6544
0
        {
6545
0
            const float NAV_RESIZE_SPEED = 600.0f;
6546
0
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6547
0
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6548
0
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
6549
0
            g.NavWindowingToggleLayer = false;
6550
0
            g.NavDisableMouseHover = true;
6551
0
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6552
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaSize);
6553
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6554
0
            {
6555
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6556
0
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6557
0
                g.NavWindowingAccumDeltaSize -= accum_floored;
6558
0
            }
6559
0
        }
6560
0
    }
6561
6562
    // Apply back modified position/size to window
6563
10.2k
    const ImVec2 curr_pos = window->Pos;
6564
10.2k
    const ImVec2 curr_size = window->SizeFull;
6565
10.2k
    if (size_target.x != FLT_MAX && (window->Size.x != size_target.x || window->SizeFull.x != size_target.x))
6566
0
        window->Size.x = window->SizeFull.x = size_target.x;
6567
10.2k
    if (size_target.y != FLT_MAX && (window->Size.y != size_target.y || window->SizeFull.y != size_target.y))
6568
0
        window->Size.y = window->SizeFull.y = size_target.y;
6569
10.2k
    if (pos_target.x != FLT_MAX && window->Pos.x != ImTrunc(pos_target.x))
6570
0
        window->Pos.x = ImTrunc(pos_target.x);
6571
10.2k
    if (pos_target.y != FLT_MAX && window->Pos.y != ImTrunc(pos_target.y))
6572
0
        window->Pos.y = ImTrunc(pos_target.y);
6573
10.2k
    if (curr_pos.x != window->Pos.x || curr_pos.y != window->Pos.y || curr_size.x != window->SizeFull.x || curr_size.y != window->SizeFull.y)
6574
0
        MarkIniSettingsDirty(window);
6575
6576
    // Recalculate next expected border expected coordinates
6577
10.2k
    if (*border_held != -1)
6578
0
        g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6579
6580
10.2k
    return ret_auto_fit_mask;
6581
68.7k
}
6582
6583
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6584
116k
{
6585
116k
    ImGuiContext& g = *GImGui;
6586
116k
    ImVec2 size_for_clamping = window->Size;
6587
116k
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && window->DockNodeAsHost)
6588
0
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6589
116k
    else if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
6590
0
        size_for_clamping.y = window->TitleBarHeight;
6591
116k
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6592
116k
}
6593
6594
static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size)
6595
0
{
6596
0
    const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6597
0
    const float rounding = window->WindowRounding;
6598
0
    const ImRect border_r = GetResizeBorderRect(window, border_n, rounding, 0.0f);
6599
0
    window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6600
0
    window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6601
0
    window->DrawList->PathStroke(border_col, ImDrawFlags_None, border_size);
6602
0
}
6603
6604
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6605
78.9k
{
6606
78.9k
    ImGuiContext& g = *GImGui;
6607
78.9k
    const float border_size = window->WindowBorderSize;
6608
78.9k
    const ImU32 border_col = GetColorU32(ImGuiCol_Border);
6609
78.9k
    if (border_size > 0.0f && (window->Flags & ImGuiWindowFlags_NoBackground) == 0)
6610
74.3k
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, border_col, window->WindowRounding, 0, window->WindowBorderSize);
6611
4.61k
    else if (border_size > 0.0f)
6612
0
    {
6613
0
        if (window->ChildFlags & ImGuiChildFlags_ResizeX) // Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border.
6614
0
            RenderWindowOuterSingleBorder(window, 1, border_col, border_size);
6615
0
        if (window->ChildFlags & ImGuiChildFlags_ResizeY)
6616
0
            RenderWindowOuterSingleBorder(window, 3, border_col, border_size);
6617
0
    }
6618
78.9k
    if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
6619
0
    {
6620
0
        const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
6621
0
        const ImU32 border_col_resizing = GetColorU32((window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
6622
0
        RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0f, window->WindowBorderSize)); // Thicker than usual
6623
0
    }
6624
78.9k
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6625
0
    {
6626
0
        float y = window->Pos.y + window->TitleBarHeight - 1;
6627
0
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), border_col, g.Style.FrameBorderSize);
6628
0
    }
6629
78.9k
}
6630
6631
// Draw background and borders
6632
// Draw and handle scrollbars
6633
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6634
127k
{
6635
127k
    ImGuiContext& g = *GImGui;
6636
127k
    ImGuiStyle& style = g.Style;
6637
127k
    ImGuiWindowFlags flags = window->Flags;
6638
6639
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6640
127k
    IM_ASSERT(window->BeginCount == 0);
6641
127k
    window->SkipItems = false;
6642
6643
    // Draw window + handle manual resize
6644
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6645
127k
    const float window_rounding = window->WindowRounding;
6646
127k
    const float window_border_size = window->WindowBorderSize;
6647
127k
    if (window->Collapsed)
6648
48.2k
    {
6649
        // Title bar only
6650
48.2k
        const float backup_border_size = style.FrameBorderSize;
6651
48.2k
        g.Style.FrameBorderSize = window->WindowBorderSize;
6652
48.2k
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6653
48.2k
        if (window->ViewportOwned)
6654
0
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6655
48.2k
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6656
48.2k
        g.Style.FrameBorderSize = backup_border_size;
6657
48.2k
    }
6658
78.9k
    else
6659
78.9k
    {
6660
        // Window background
6661
78.9k
        if (!(flags & ImGuiWindowFlags_NoBackground))
6662
78.9k
        {
6663
78.9k
            bool is_docking_transparent_payload = false;
6664
78.9k
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6665
0
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6666
0
                    is_docking_transparent_payload = true;
6667
6668
78.9k
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6669
78.9k
            if (window->ViewportOwned)
6670
0
            {
6671
0
                bg_col |= IM_COL32_A_MASK; // No alpha
6672
0
                if (is_docking_transparent_payload)
6673
0
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6674
0
            }
6675
78.9k
            else
6676
78.9k
            {
6677
                // Adjust alpha. For docking
6678
78.9k
                bool override_alpha = false;
6679
78.9k
                float alpha = 1.0f;
6680
78.9k
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6681
0
                {
6682
0
                    alpha = g.NextWindowData.BgAlphaVal;
6683
0
                    override_alpha = true;
6684
0
                }
6685
78.9k
                if (is_docking_transparent_payload)
6686
0
                {
6687
0
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6688
0
                    override_alpha = true;
6689
0
                }
6690
78.9k
                if (override_alpha)
6691
0
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6692
78.9k
            }
6693
6694
            // Render, for docked windows and host windows we ensure bg goes before decorations
6695
78.9k
            if (window->DockIsActive)
6696
0
                window->DockNode->LastBgColor = bg_col;
6697
78.9k
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6698
78.9k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6699
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6700
78.9k
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6701
78.9k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6702
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6703
78.9k
        }
6704
78.9k
        if (window->DockIsActive)
6705
0
            window->DockNode->IsBgDrawnThisFrame = true;
6706
6707
        // Title bar
6708
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6709
        // in order for their pos/size to be matching their undocking state.)
6710
78.9k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6711
68.7k
        {
6712
68.7k
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6713
68.7k
            if (window->ViewportOwned)
6714
0
                title_bar_col |= IM_COL32_A_MASK; // No alpha
6715
68.7k
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6716
68.7k
        }
6717
6718
        // Menu bar
6719
78.9k
        if (flags & ImGuiWindowFlags_MenuBar)
6720
0
        {
6721
0
            ImRect menu_bar_rect = window->MenuBarRect();
6722
0
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6723
0
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6724
0
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6725
0
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6726
0
        }
6727
6728
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6729
78.9k
        ImGuiDockNode* node = window->DockNode;
6730
78.9k
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6731
0
        {
6732
0
            float unhide_sz_draw = ImTrunc(g.FontSize * 0.70f);
6733
0
            float unhide_sz_hit = ImTrunc(g.FontSize * 0.55f);
6734
0
            ImVec2 p = node->Pos;
6735
0
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6736
0
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6737
0
            KeepAliveID(unhide_id);
6738
0
            bool hovered, held;
6739
0
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6740
0
                node->WantHiddenTabBarToggle = true;
6741
0
            else if (held && IsMouseDragging(0))
6742
0
                StartMouseMovingWindowOrNode(window, node, true); // Undock from tab-bar triangle = same as window/collapse menu button
6743
6744
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6745
0
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6746
0
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6747
0
        }
6748
6749
        // Scrollbars
6750
78.9k
        if (window->ScrollbarX)
6751
10.2k
            Scrollbar(ImGuiAxis_X);
6752
78.9k
        if (window->ScrollbarY)
6753
9.73k
            Scrollbar(ImGuiAxis_Y);
6754
6755
        // Render resize grips (after their input handling so we don't have a frame of latency)
6756
78.9k
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6757
68.7k
        {
6758
206k
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6759
137k
            {
6760
137k
                const ImU32 col = resize_grip_col[resize_grip_n];
6761
137k
                if ((col & IM_COL32_A_MASK) == 0)
6762
127k
                    continue;
6763
10.2k
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6764
10.2k
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6765
10.2k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6766
10.2k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6767
10.2k
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6768
10.2k
                window->DrawList->PathFillConvex(col);
6769
10.2k
            }
6770
68.7k
        }
6771
6772
        // Borders (for dock node host they will be rendered over after the tab bar)
6773
78.9k
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6774
78.9k
            RenderWindowOuterBorders(window);
6775
78.9k
    }
6776
127k
}
6777
6778
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6779
// Render title text, collapse button, close button
6780
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6781
116k
{
6782
116k
    ImGuiContext& g = *GImGui;
6783
116k
    ImGuiStyle& style = g.Style;
6784
116k
    ImGuiWindowFlags flags = window->Flags;
6785
6786
116k
    const bool has_close_button = (p_open != NULL);
6787
116k
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6788
6789
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6790
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6791
116k
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6792
116k
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6793
116k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6794
6795
    // Layout buttons
6796
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6797
116k
    float pad_l = style.FramePadding.x;
6798
116k
    float pad_r = style.FramePadding.x;
6799
116k
    float button_sz = g.FontSize;
6800
116k
    ImVec2 close_button_pos;
6801
116k
    ImVec2 collapse_button_pos;
6802
116k
    if (has_close_button)
6803
0
    {
6804
0
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6805
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6806
0
    }
6807
116k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6808
0
    {
6809
0
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6810
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6811
0
    }
6812
116k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6813
116k
    {
6814
116k
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
6815
116k
        pad_l += button_sz + style.ItemInnerSpacing.x;
6816
116k
    }
6817
6818
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6819
116k
    if (has_collapse_button)
6820
116k
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6821
1
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6822
6823
    // Close button
6824
116k
    if (has_close_button)
6825
0
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6826
0
            *p_open = false;
6827
6828
116k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6829
116k
    g.CurrentItemFlags = item_flags_backup;
6830
6831
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6832
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6833
116k
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6834
116k
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6835
6836
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6837
    // while uncentered title text will still reach edges correctly.
6838
116k
    if (pad_l > style.FramePadding.x)
6839
116k
        pad_l += g.Style.ItemInnerSpacing.x;
6840
116k
    if (pad_r > style.FramePadding.x)
6841
0
        pad_r += g.Style.ItemInnerSpacing.x;
6842
116k
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6843
0
    {
6844
0
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6845
0
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6846
0
        pad_l = ImMax(pad_l, pad_extend * centerness);
6847
0
        pad_r = ImMax(pad_r, pad_extend * centerness);
6848
0
    }
6849
6850
116k
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6851
116k
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6852
116k
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6853
0
    {
6854
0
        ImVec2 marker_pos;
6855
0
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6856
0
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6857
0
        if (marker_pos.x > layout_r.Min.x)
6858
0
        {
6859
0
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6860
0
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6861
0
        }
6862
0
    }
6863
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6864
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6865
116k
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6866
116k
}
6867
6868
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6869
127k
{
6870
127k
    window->ParentWindow = parent_window;
6871
127k
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6872
127k
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6873
10.2k
    {
6874
10.2k
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6875
10.2k
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6876
10.2k
            window->RootWindow = parent_window->RootWindow;
6877
10.2k
    }
6878
127k
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6879
0
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6880
127k
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6881
10.2k
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6882
127k
    while (window->RootWindowForNav->ChildFlags & ImGuiChildFlags_NavFlattened)
6883
0
    {
6884
0
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6885
0
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6886
0
    }
6887
127k
}
6888
6889
// [EXPERIMENTAL] Called by Begin(). NextWindowData is valid at this point.
6890
// This is designed as a toy/test-bed for
6891
void ImGui::UpdateWindowSkipRefresh(ImGuiWindow* window)
6892
127k
{
6893
127k
    ImGuiContext& g = *GImGui;
6894
127k
    window->SkipRefresh = false;
6895
127k
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasRefreshPolicy) == 0)
6896
127k
        return;
6897
0
    if (g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_TryToAvoidRefresh)
6898
0
    {
6899
        // FIXME-IDLE: Tests for e.g. mouse clicks or keyboard while focused.
6900
0
        if (window->Appearing) // If currently appearing
6901
0
            return;
6902
0
        if (window->Hidden) // If was hidden (previous frame)
6903
0
            return;
6904
0
        if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnHover) && g.HoveredWindow && window->RootWindow == g.HoveredWindow->RootWindow)
6905
0
            return;
6906
0
        if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnFocus) && g.NavWindow && window->RootWindow == g.NavWindow->RootWindow)
6907
0
            return;
6908
0
        window->DrawList = NULL;
6909
0
        window->SkipRefresh = true;
6910
0
    }
6911
0
}
6912
6913
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6914
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6915
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6916
// - WindowA            // FindBlockingModal() returns Modal1
6917
//   - WindowB          //                  .. returns Modal1
6918
//   - Modal1           //                  .. returns Modal2
6919
//      - WindowC       //                  .. returns Modal2
6920
//          - WindowD   //                  .. returns Modal2
6921
//          - Modal2    //                  .. returns Modal2
6922
//            - WindowE //                  .. returns NULL
6923
// Notes:
6924
// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
6925
//   Only difference is here we check for ->Active/WasActive but it may be unnecessary.
6926
ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6927
44
{
6928
44
    ImGuiContext& g = *GImGui;
6929
44
    if (g.OpenPopupStack.Size <= 0)
6930
44
        return NULL;
6931
6932
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6933
0
    for (ImGuiPopupData& popup_data : g.OpenPopupStack)
6934
0
    {
6935
0
        ImGuiWindow* popup_window = popup_data.Window;
6936
0
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6937
0
            continue;
6938
0
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6939
0
            continue;
6940
0
        if (window == NULL)                                         // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
6941
0
            return popup_window;
6942
0
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window may be over modal
6943
0
            continue;
6944
0
        return popup_window;                                        // Place window right below first block modal
6945
0
    }
6946
0
    return NULL;
6947
0
}
6948
6949
// Push a new Dear ImGui window to add widgets to.
6950
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6951
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6952
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6953
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6954
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6955
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6956
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6957
127k
{
6958
127k
    ImGuiContext& g = *GImGui;
6959
127k
    const ImGuiStyle& style = g.Style;
6960
127k
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6961
127k
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6962
127k
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6963
6964
    // Find or create
6965
127k
    ImGuiWindow* window = FindWindowByName(name);
6966
127k
    const bool window_just_created = (window == NULL);
6967
127k
    if (window_just_created)
6968
3
        window = CreateNewWindow(name, flags);
6969
6970
    // [DEBUG] Debug break requested by user
6971
127k
    if (g.DebugBreakInWindow == window->ID)
6972
0
        IM_DEBUG_BREAK();
6973
6974
    // Automatically disable manual moving/resizing when NoInputs is set
6975
127k
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6976
0
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6977
6978
127k
    const int current_frame = g.FrameCount;
6979
127k
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6980
127k
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6981
6982
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6983
127k
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6984
127k
    if (flags & ImGuiWindowFlags_Popup)
6985
0
    {
6986
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6987
0
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6988
0
        window_just_activated_by_user |= (window != popup_ref.Window);
6989
0
    }
6990
6991
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6992
127k
    const bool window_was_appearing = window->Appearing;
6993
127k
    if (first_begin_of_the_frame)
6994
127k
    {
6995
127k
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6996
127k
        window->Appearing = window_just_activated_by_user;
6997
127k
        if (window->Appearing)
6998
3
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6999
127k
        window->FlagsPreviousFrame = window->Flags;
7000
127k
        window->Flags = (ImGuiWindowFlags)flags;
7001
127k
        window->ChildFlags = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
7002
127k
        window->LastFrameActive = current_frame;
7003
127k
        window->LastTimeActive = (float)g.Time;
7004
127k
        window->BeginOrderWithinParent = 0;
7005
127k
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
7006
127k
    }
7007
0
    else
7008
0
    {
7009
0
        flags = window->Flags;
7010
0
    }
7011
7012
    // Docking
7013
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
7014
127k
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
7015
127k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
7016
0
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
7017
127k
    if (first_begin_of_the_frame)
7018
127k
    {
7019
127k
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
7020
127k
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
7021
127k
        bool dock_node_was_visible = window->DockNodeIsVisible;
7022
127k
        bool dock_tab_was_visible = window->DockTabIsVisible;
7023
127k
        if (has_dock_node || new_auto_dock_node)
7024
0
        {
7025
0
            BeginDocked(window, p_open);
7026
0
            flags = window->Flags;
7027
0
            if (window->DockIsActive)
7028
0
            {
7029
0
                IM_ASSERT(window->DockNode != NULL);
7030
0
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
7031
0
            }
7032
7033
            // Amend the Appearing flag
7034
0
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
7035
0
            {
7036
0
                window->Appearing = true;
7037
0
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
7038
0
            }
7039
0
        }
7040
127k
        else
7041
127k
        {
7042
127k
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
7043
127k
        }
7044
127k
    }
7045
7046
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
7047
127k
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
7048
127k
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
7049
127k
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
7050
7051
    // We allow window memory to be compacted so recreate the base stack when needed.
7052
127k
    if (window->IDStack.Size == 0)
7053
0
        window->IDStack.push_back(window->ID);
7054
7055
    // Add to stack
7056
127k
    g.CurrentWindow = window;
7057
127k
    ImGuiWindowStackData window_stack_data;
7058
127k
    window_stack_data.Window = window;
7059
127k
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
7060
127k
    window_stack_data.StackSizesOnBegin.SetToContextState(&g);
7061
127k
    window_stack_data.DisabledOverrideReenable = (flags & ImGuiWindowFlags_Tooltip) && (g.CurrentItemFlags & ImGuiItemFlags_Disabled);
7062
127k
    g.CurrentWindowStack.push_back(window_stack_data);
7063
127k
    if (flags & ImGuiWindowFlags_ChildMenu)
7064
0
        g.BeginMenuDepth++;
7065
7066
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
7067
127k
    if (first_begin_of_the_frame)
7068
127k
    {
7069
127k
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
7070
127k
        window->ParentWindowInBeginStack = parent_window_in_stack;
7071
7072
        // Focus route
7073
        // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack,
7074
        // Use for e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798)
7075
127k
        window->ParentWindowForFocusRoute = (window->RootWindow != window) ? parent_window_in_stack : NULL;
7076
127k
        if (window->ParentWindowForFocusRoute == NULL && window->DockNode != NULL)
7077
0
            if (window->DockNode->MergedFlags & ImGuiDockNodeFlags_DockedWindowsInFocusRoute)
7078
0
                window->ParentWindowForFocusRoute = window->DockNode->HostWindow;
7079
7080
        // Override with SetNextWindowClass() field or direct call to SetWindowParentWindowForFocusRoute()
7081
127k
        if (window->WindowClass.FocusRouteParentWindowId != 0)
7082
0
        {
7083
0
            window->ParentWindowForFocusRoute = FindWindowByID(window->WindowClass.FocusRouteParentWindowId);
7084
0
            IM_ASSERT(window->ParentWindowForFocusRoute != 0); // Invalid value for FocusRouteParentWindowId.
7085
0
        }
7086
127k
    }
7087
7088
    // Add to focus scope stack
7089
127k
    PushFocusScope((window->ChildFlags & ImGuiChildFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID);
7090
127k
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
7091
7092
    // Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[]
7093
127k
    if (flags & ImGuiWindowFlags_Popup)
7094
0
    {
7095
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
7096
0
        popup_ref.Window = window;
7097
0
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
7098
0
        g.BeginPopupStack.push_back(popup_ref);
7099
0
        window->PopupId = popup_ref.PopupId;
7100
0
    }
7101
7102
    // Process SetNextWindow***() calls
7103
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
7104
127k
    bool window_pos_set_by_api = false;
7105
127k
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
7106
127k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
7107
0
    {
7108
0
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
7109
0
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
7110
0
        {
7111
            // May be processed on the next frame if this is our first frame and we are measuring size
7112
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
7113
0
            window->SetWindowPosVal = g.NextWindowData.PosVal;
7114
0
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
7115
0
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7116
0
        }
7117
0
        else
7118
0
        {
7119
0
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
7120
0
        }
7121
0
    }
7122
127k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
7123
68.7k
    {
7124
68.7k
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
7125
68.7k
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
7126
68.7k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
7127
0
            g.NextWindowData.SizeVal.x = window->SizeFull.x;
7128
68.7k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
7129
0
            g.NextWindowData.SizeVal.y = window->SizeFull.y;
7130
68.7k
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
7131
68.7k
    }
7132
127k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
7133
0
    {
7134
0
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
7135
0
        {
7136
0
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
7137
0
            window->ScrollTargetCenterRatio.x = 0.0f;
7138
0
        }
7139
0
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
7140
0
        {
7141
0
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
7142
0
            window->ScrollTargetCenterRatio.y = 0.0f;
7143
0
        }
7144
0
    }
7145
127k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
7146
0
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
7147
127k
    else if (first_begin_of_the_frame)
7148
127k
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
7149
127k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
7150
0
        window->WindowClass = g.NextWindowData.WindowClass;
7151
127k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
7152
0
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
7153
127k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
7154
0
        FocusWindow(window);
7155
127k
    if (window->Appearing)
7156
3
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
7157
7158
    // [EXPERIMENTAL] Skip Refresh mode
7159
127k
    UpdateWindowSkipRefresh(window);
7160
7161
    // Nested root windows (typically tooltips) override disabled state
7162
127k
    if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
7163
0
        BeginDisabledOverrideReenable();
7164
7165
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
7166
127k
    g.CurrentWindow = NULL;
7167
7168
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
7169
127k
    if (first_begin_of_the_frame && !window->SkipRefresh)
7170
127k
    {
7171
        // Initialize
7172
127k
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
7173
127k
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
7174
127k
        window->Active = true;
7175
127k
        window->HasCloseButton = (p_open != NULL);
7176
127k
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
7177
127k
        window->IDStack.resize(1);
7178
127k
        window->DrawList->_ResetForNewFrame();
7179
127k
        window->DC.CurrentTableIdx = -1;
7180
127k
        if (flags & ImGuiWindowFlags_DockNodeHost)
7181
0
        {
7182
0
            window->DrawList->ChannelsSplit(2);
7183
0
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
7184
0
        }
7185
7186
        // Restore buffer capacity when woken from a compacted state, to avoid
7187
127k
        if (window->MemoryCompacted)
7188
0
            GcAwakeTransientWindowBuffers(window);
7189
7190
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
7191
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
7192
127k
        bool window_title_visible_elsewhere = false;
7193
127k
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
7194
0
            window_title_visible_elsewhere = true;
7195
127k
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
7196
0
            window_title_visible_elsewhere = true;
7197
127k
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
7198
0
        {
7199
0
            size_t buf_len = (size_t)window->NameBufLen;
7200
0
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
7201
0
            window->NameBufLen = (int)buf_len;
7202
0
        }
7203
7204
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
7205
7206
        // Update contents size from last frame for auto-fitting (or use explicit size)
7207
127k
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
7208
7209
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
7210
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
7211
        // it has a single usage before this code block and may be set below before it is finally checked.
7212
127k
        if (window->HiddenFramesCanSkipItems > 0)
7213
10.1k
            window->HiddenFramesCanSkipItems--;
7214
127k
        if (window->HiddenFramesCannotSkipItems > 0)
7215
2
            window->HiddenFramesCannotSkipItems--;
7216
127k
        if (window->HiddenFramesForRenderOnly > 0)
7217
0
            window->HiddenFramesForRenderOnly--;
7218
7219
        // Hide new windows for one frame until they calculate their size
7220
127k
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
7221
2
            window->HiddenFramesCannotSkipItems = 1;
7222
7223
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
7224
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
7225
127k
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
7226
0
        {
7227
0
            window->HiddenFramesCannotSkipItems = 1;
7228
0
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
7229
0
            {
7230
0
                if (!window_size_x_set_by_api)
7231
0
                    window->Size.x = window->SizeFull.x = 0.f;
7232
0
                if (!window_size_y_set_by_api)
7233
0
                    window->Size.y = window->SizeFull.y = 0.f;
7234
0
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
7235
0
            }
7236
0
        }
7237
7238
        // SELECT VIEWPORT
7239
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
7240
7241
127k
        WindowSelectViewport(window);
7242
127k
        SetCurrentViewport(window, window->Viewport);
7243
127k
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7244
127k
        SetCurrentWindow(window);
7245
127k
        flags = window->Flags;
7246
7247
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
7248
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
7249
7250
127k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow))
7251
10.2k
            window->WindowBorderSize = style.ChildBorderSize;
7252
116k
        else
7253
116k
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
7254
127k
        window->WindowPadding = style.WindowPadding;
7255
127k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
7256
4.61k
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
7257
7258
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
7259
127k
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
7260
127k
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
7261
127k
        window->TitleBarHeight = (flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : g.FontSize + g.Style.FramePadding.y * 2.0f;
7262
127k
        window->MenuBarHeight = (flags & ImGuiWindowFlags_MenuBar) ? window->DC.MenuBarOffset.y + g.FontSize + g.Style.FramePadding.y * 2.0f : 0.0f;
7263
7264
        // Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible.
7265
        // Those flags will be altered further down in the function depending on more conditions.
7266
127k
        bool use_current_size_for_scrollbar_x = window_just_created;
7267
127k
        bool use_current_size_for_scrollbar_y = window_just_created;
7268
127k
        if (window_size_x_set_by_api && window->ContentSizeExplicit.x != 0.0f)
7269
0
            use_current_size_for_scrollbar_x = true;
7270
127k
        if (window_size_y_set_by_api && window->ContentSizeExplicit.y != 0.0f) // #7252
7271
0
            use_current_size_for_scrollbar_y = true;
7272
7273
        // Collapse window by double-clicking on title bar
7274
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
7275
127k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
7276
116k
        {
7277
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
7278
116k
            ImRect title_bar_rect = window->TitleBarRect();
7279
116k
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max))
7280
35
                if (g.IO.MouseClickedCount[0] == 2 && GetKeyOwner(ImGuiKey_MouseLeft) == ImGuiKeyOwner_NoOwner)
7281
0
                    window->WantCollapseToggle = true;
7282
116k
            if (window->WantCollapseToggle)
7283
1
            {
7284
1
                window->Collapsed = !window->Collapsed;
7285
1
                if (!window->Collapsed)
7286
0
                    use_current_size_for_scrollbar_y = true;
7287
1
                MarkIniSettingsDirty(window);
7288
1
            }
7289
116k
        }
7290
10.2k
        else
7291
10.2k
        {
7292
10.2k
            window->Collapsed = false;
7293
10.2k
        }
7294
127k
        window->WantCollapseToggle = false;
7295
7296
        // SIZE
7297
7298
        // Outer Decoration Sizes
7299
        // (we need to clear ScrollbarSize immediately as CalcWindowAutoFitSize() needs it and can be called from other locations).
7300
127k
        const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
7301
127k
        window->DecoOuterSizeX1 = 0.0f;
7302
127k
        window->DecoOuterSizeX2 = 0.0f;
7303
127k
        window->DecoOuterSizeY1 = window->TitleBarHeight + window->MenuBarHeight;
7304
127k
        window->DecoOuterSizeY2 = 0.0f;
7305
127k
        window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
7306
7307
        // Calculate auto-fit size, handle automatic resize
7308
127k
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
7309
127k
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
7310
0
        {
7311
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
7312
0
            if (!window_size_x_set_by_api)
7313
0
            {
7314
0
                window->SizeFull.x = size_auto_fit.x;
7315
0
                use_current_size_for_scrollbar_x = true;
7316
0
            }
7317
0
            if (!window_size_y_set_by_api)
7318
0
            {
7319
0
                window->SizeFull.y = size_auto_fit.y;
7320
0
                use_current_size_for_scrollbar_y = true;
7321
0
            }
7322
0
        }
7323
127k
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7324
4
        {
7325
            // Auto-fit may only grow window during the first few frames
7326
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
7327
4
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
7328
2
            {
7329
2
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
7330
2
                use_current_size_for_scrollbar_x = true;
7331
2
            }
7332
4
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
7333
3
            {
7334
3
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
7335
3
                use_current_size_for_scrollbar_y = true;
7336
3
            }
7337
4
            if (!window->Collapsed)
7338
4
                MarkIniSettingsDirty(window);
7339
4
        }
7340
7341
        // Apply minimum/maximum window size constraints and final size
7342
127k
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
7343
127k
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
7344
7345
        // POSITION
7346
7347
        // Popup latch its initial position, will position itself when it appears next frame
7348
127k
        if (window_just_activated_by_user)
7349
3
        {
7350
3
            window->AutoPosLastDirection = ImGuiDir_None;
7351
3
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
7352
0
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
7353
3
        }
7354
7355
        // Position child window
7356
127k
        if (flags & ImGuiWindowFlags_ChildWindow)
7357
10.2k
        {
7358
10.2k
            IM_ASSERT(parent_window && parent_window->Active);
7359
10.2k
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
7360
10.2k
            parent_window->DC.ChildWindows.push_back(window);
7361
10.2k
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
7362
10.2k
                window->Pos = parent_window->DC.CursorPos;
7363
10.2k
        }
7364
7365
127k
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
7366
127k
        if (window_pos_with_pivot)
7367
0
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
7368
127k
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
7369
0
            window->Pos = FindBestWindowPosForPopup(window);
7370
127k
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
7371
0
            window->Pos = FindBestWindowPosForPopup(window);
7372
127k
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
7373
0
            window->Pos = FindBestWindowPosForPopup(window);
7374
7375
        // Late create viewport if we don't fit within our current host viewport.
7376
127k
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
7377
0
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
7378
0
            {
7379
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
7380
                //ImGuiViewport* old_viewport = window->Viewport;
7381
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
7382
7383
                // FIXME-DPI
7384
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
7385
0
                SetCurrentViewport(window, window->Viewport);
7386
0
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7387
0
                SetCurrentWindow(window);
7388
0
            }
7389
7390
127k
        if (window->ViewportOwned)
7391
0
            WindowSyncOwnedViewport(window, parent_window_in_stack);
7392
7393
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
7394
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
7395
127k
        ImRect viewport_rect(window->Viewport->GetMainRect());
7396
127k
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
7397
127k
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
7398
127k
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
7399
7400
        // Clamp position/size so window stays visible within its viewport or monitor
7401
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
7402
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
7403
127k
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
7404
116k
        {
7405
116k
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
7406
116k
            {
7407
116k
                ClampWindowPos(window, visibility_rect);
7408
116k
            }
7409
0
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
7410
0
            {
7411
0
                if (g.MovingWindow != NULL && window->RootWindowDockTree == g.MovingWindow->RootWindowDockTree)
7412
0
                {
7413
                    // While moving windows we allow them to straddle monitors (#7299, #3071)
7414
0
                    visibility_rect = g.PlatformMonitorsFullWorkRect;
7415
0
                }
7416
0
                else
7417
0
                {
7418
                    // When not moving ensure visible in its monitor
7419
                    // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
7420
0
                    const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
7421
0
                    visibility_rect = ImRect(monitor->WorkPos, monitor->WorkPos + monitor->WorkSize);
7422
0
                }
7423
0
                visibility_rect.Expand(-visibility_padding);
7424
0
                ClampWindowPos(window, visibility_rect);
7425
0
            }
7426
116k
        }
7427
127k
        window->Pos = ImTrunc(window->Pos);
7428
7429
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
7430
        // Large values tend to lead to variety of artifacts and are not recommended.
7431
127k
        if (window->ViewportOwned || window->DockIsActive)
7432
0
            window->WindowRounding = 0.0f;
7433
127k
        else
7434
127k
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
7435
7436
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
7437
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7438
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
7439
7440
        // Apply window focus (new and reactivated windows are moved to front)
7441
127k
        bool want_focus = false;
7442
127k
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
7443
3
        {
7444
3
            if (flags & ImGuiWindowFlags_Popup)
7445
0
                want_focus = true;
7446
3
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
7447
2
                want_focus = true;
7448
3
        }
7449
7450
        // [Test Engine] Register whole window in the item system (before submitting further decorations)
7451
#ifdef IMGUI_ENABLE_TEST_ENGINE
7452
        if (g.TestEngineHookItems)
7453
        {
7454
            IM_ASSERT(window->IDStack.Size == 1);
7455
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
7456
            IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
7457
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
7458
            window->IDStack.Size = 1;
7459
        }
7460
#endif
7461
7462
        // Decide if we are going to handle borders and resize grips
7463
127k
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
7464
7465
        // Handle manual resize: Resize Grips, Borders, Gamepad
7466
127k
        int border_hovered = -1, border_held = -1;
7467
127k
        ImU32 resize_grip_col[4] = {};
7468
127k
        const int resize_grip_count = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) ? 0 : g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
7469
127k
        const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7470
127k
        if (handle_borders_and_resize_grips && !window->Collapsed)
7471
78.9k
            if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
7472
0
            {
7473
0
                if (auto_fit_mask & (1 << ImGuiAxis_X))
7474
0
                    use_current_size_for_scrollbar_x = true;
7475
0
                if (auto_fit_mask & (1 << ImGuiAxis_Y))
7476
0
                    use_current_size_for_scrollbar_y = true;
7477
0
            }
7478
127k
        window->ResizeBorderHovered = (signed char)border_hovered;
7479
127k
        window->ResizeBorderHeld = (signed char)border_held;
7480
7481
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
7482
127k
        if (window->ViewportOwned)
7483
0
        {
7484
0
            if (!window->Viewport->PlatformRequestMove)
7485
0
                window->Viewport->Pos = window->Pos;
7486
0
            if (!window->Viewport->PlatformRequestResize)
7487
0
                window->Viewport->Size = window->Size;
7488
0
            window->Viewport->UpdateWorkRect();
7489
0
            viewport_rect = window->Viewport->GetMainRect();
7490
0
        }
7491
7492
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
7493
127k
        window->ViewportPos = window->Viewport->Pos;
7494
7495
        // SCROLLBAR VISIBILITY
7496
7497
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
7498
127k
        if (!window->Collapsed)
7499
78.9k
        {
7500
            // When reading the current size we need to read it after size constraints have been applied.
7501
            // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
7502
            // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
7503
78.9k
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
7504
78.9k
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
7505
78.9k
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
7506
78.9k
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
7507
78.9k
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
7508
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
7509
78.9k
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
7510
78.9k
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
7511
78.9k
            if (window->ScrollbarX && !window->ScrollbarY)
7512
2.52k
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
7513
78.9k
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
7514
7515
            // Amend the partially filled window->DecorationXXX values.
7516
78.9k
            window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
7517
78.9k
            window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
7518
78.9k
        }
7519
7520
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
7521
        // Update various regions. Variables they depend on should be set above in this function.
7522
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
7523
7524
        // Outer rectangle
7525
        // Not affected by window border size. Used by:
7526
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7527
        // - Begin() initial clipping rect for drawing window background and borders.
7528
        // - Begin() clipping whole child
7529
127k
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7530
127k
        const ImRect outer_rect = window->Rect();
7531
127k
        const ImRect title_bar_rect = window->TitleBarRect();
7532
127k
        window->OuterRectClipped = outer_rect;
7533
127k
        if (window->DockIsActive)
7534
0
            window->OuterRectClipped.Min.y += window->TitleBarHeight;
7535
127k
        window->OuterRectClipped.ClipWith(host_rect);
7536
7537
        // Inner rectangle
7538
        // Not affected by window border size. Used by:
7539
        // - InnerClipRect
7540
        // - ScrollToRectEx()
7541
        // - NavUpdatePageUpPageDown()
7542
        // - Scrollbar()
7543
127k
        window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
7544
127k
        window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7545
127k
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7546
127k
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7547
7548
        // Inner clipping rectangle.
7549
        // - Extend a outside of normal work region up to borders.
7550
        // - This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7551
        // - It also makes clipped items be more noticeable.
7552
        // - And is consistent on both axis (prior to 2024/05/03 ClipRect used WindowPadding.x * 0.5f on left and right edge), see #3312
7553
        // - Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7554
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7555
        // Affected by window/frame border size. Used by:
7556
        // - Begin() initial clip rect
7557
127k
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7558
127k
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + window->WindowBorderSize);
7559
127k
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
7560
127k
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - window->WindowBorderSize);
7561
127k
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7562
127k
        window->InnerClipRect.ClipWithFull(host_rect);
7563
7564
        // Default item width. Make it proportional to window size if window manually resizes
7565
127k
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7566
127k
            window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f);
7567
0
        else
7568
0
            window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f);
7569
7570
        // SCROLLING
7571
7572
        // Lock down maximum scrolling
7573
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7574
        // for right/bottom aligned items without creating a scrollbar.
7575
127k
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7576
127k
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7577
7578
        // Apply scrolling
7579
127k
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7580
127k
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7581
127k
        window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7582
7583
        // DRAWING
7584
7585
        // Setup draw list and outer clipping rectangle
7586
127k
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7587
127k
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
7588
127k
        PushClipRect(host_rect.Min, host_rect.Max, false);
7589
7590
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7591
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7592
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
7593
127k
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
7594
127k
        if (is_undocked_or_docked_visible)
7595
127k
        {
7596
127k
            bool render_decorations_in_parent = false;
7597
127k
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7598
10.2k
            {
7599
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7600
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7601
10.2k
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7602
10.2k
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
7603
10.2k
                bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
7604
10.2k
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
7605
10.2k
                    render_decorations_in_parent = true;
7606
10.2k
            }
7607
127k
            if (render_decorations_in_parent)
7608
10.2k
                window->DrawList = parent_window->DrawList;
7609
7610
            // Handle title bar, scrollbar, resize grips and resize borders
7611
127k
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7612
127k
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
7613
127k
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7614
7615
127k
            if (render_decorations_in_parent)
7616
10.2k
                window->DrawList = &window->DrawListInst;
7617
127k
        }
7618
7619
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7620
7621
        // Work rectangle.
7622
        // Affected by window padding and border size. Used by:
7623
        // - Columns() for right-most edge
7624
        // - TreeNode(), CollapsingHeader() for right-most edge
7625
        // - BeginTabBar() for right-most edge
7626
127k
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7627
127k
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7628
127k
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7629
127k
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7630
127k
        window->WorkRect.Min.x = ImTrunc(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7631
127k
        window->WorkRect.Min.y = ImTrunc(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7632
127k
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7633
127k
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7634
127k
        window->ParentWorkRect = window->WorkRect;
7635
7636
        // [LEGACY] Content Region
7637
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7638
        // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
7639
        // Used by:
7640
        // - Mouse wheel scrolling + many other things
7641
127k
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7642
127k
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7643
127k
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7644
127k
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7645
7646
        // Setup drawing context
7647
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7648
127k
        window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7649
127k
        window->DC.GroupOffset.x = 0.0f;
7650
127k
        window->DC.ColumnsOffset.x = 0.0f;
7651
7652
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7653
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7654
127k
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7655
127k
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7656
127k
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7657
127k
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7658
127k
        window->DC.CursorPos = window->DC.CursorStartPos;
7659
127k
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7660
127k
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7661
127k
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7662
127k
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7663
127k
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7664
127k
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7665
7666
127k
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7667
127k
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7668
127k
        window->DC.NavLayersActiveMaskNext = 0x00;
7669
127k
        window->DC.NavIsScrollPushableX = true;
7670
127k
        window->DC.NavHideHighlightOneFrame = false;
7671
127k
        window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
7672
7673
127k
        window->DC.MenuBarAppending = false;
7674
127k
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7675
127k
        window->DC.TreeDepth = 0;
7676
127k
        window->DC.TreeHasStackDataDepthMask = 0x00;
7677
127k
        window->DC.ChildWindows.resize(0);
7678
127k
        window->DC.StateStorage = &window->StateStorage;
7679
127k
        window->DC.CurrentColumns = NULL;
7680
127k
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7681
127k
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7682
7683
127k
        window->DC.ItemWidth = window->ItemWidthDefault;
7684
127k
        window->DC.TextWrapPos = -1.0f; // disabled
7685
127k
        window->DC.ItemWidthStack.resize(0);
7686
127k
        window->DC.TextWrapPosStack.resize(0);
7687
127k
        if (flags & ImGuiWindowFlags_Modal)
7688
0
            window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(GetStyleColorVec4(ImGuiCol_ModalWindowDimBg));
7689
7690
127k
        if (window->AutoFitFramesX > 0)
7691
2
            window->AutoFitFramesX--;
7692
127k
        if (window->AutoFitFramesY > 0)
7693
4
            window->AutoFitFramesY--;
7694
7695
        // Clear SetNextWindowXXX data (can aim to move this higher in the function)
7696
127k
        g.NextWindowData.ClearFlags();
7697
7698
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7699
        // We ImGuiFocusRequestFlags_UnlessBelowModal to:
7700
        // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
7701
        // - Position window behind the modal that is not a begin-parent of this window.
7702
127k
        if (want_focus)
7703
2
            FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
7704
127k
        if (want_focus && window == g.NavWindow)
7705
2
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7706
7707
        // Close requested by platform window (apply to all windows in this viewport)
7708
127k
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7709
0
        {
7710
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
7711
0
            *p_open = false;
7712
0
            g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. // FIXME-NAV: Try removing.
7713
0
        }
7714
7715
        // Title bar
7716
127k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7717
116k
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7718
7719
        // Clear hit test shape every frame
7720
127k
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7721
7722
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7723
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7724
        // Maybe we can support CTRL+C on every element?
7725
        /*
7726
        //if (g.NavWindow == window && g.ActiveId == 0)
7727
        if (g.ActiveId == window->MoveId)
7728
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7729
                LogToClipboard();
7730
        */
7731
7732
127k
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7733
127k
        {
7734
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7735
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7736
127k
            if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7737
91
                BeginDockableDragDropSource(window);
7738
7739
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7740
127k
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7741
183
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7742
93
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7743
93
                        BeginDockableDragDropTarget(window);
7744
127k
        }
7745
7746
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7747
        // This is useful to allow creating context menus on title bar only, etc.
7748
127k
        SetLastItemDataForWindow(window, title_bar_rect);
7749
7750
        // [DEBUG]
7751
127k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7752
127k
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7753
0
            DebugLocateItemResolveWithLastItem();
7754
127k
#endif
7755
7756
        // [Test Engine] Register title bar / tab with MoveId.
7757
#ifdef IMGUI_ENABLE_TEST_ENGINE
7758
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7759
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7760
#endif
7761
127k
    }
7762
0
    else
7763
0
    {
7764
        // Skip refresh always mark active
7765
0
        if (window->SkipRefresh)
7766
0
            window->Active = true;
7767
7768
        // Append
7769
0
        SetCurrentViewport(window, window->Viewport);
7770
0
        SetCurrentWindow(window);
7771
0
        g.NextWindowData.ClearFlags();
7772
0
        SetLastItemDataForWindow(window, window->TitleBarRect());
7773
0
    }
7774
7775
127k
    if (!(flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh)
7776
127k
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7777
7778
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7779
127k
    window->WriteAccessed = false;
7780
127k
    window->BeginCount++;
7781
7782
    // Update visibility
7783
127k
    if (first_begin_of_the_frame && !window->SkipRefresh)
7784
127k
    {
7785
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7786
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7787
        // This is analogous to regular windows being hidden from one frame.
7788
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7789
127k
        if (window->DockIsActive && !window->DockTabIsVisible)
7790
0
        {
7791
0
            if (window->LastFrameJustFocused == g.FrameCount)
7792
0
                window->HiddenFramesCannotSkipItems = 1;
7793
0
            else
7794
0
                window->HiddenFramesCanSkipItems = 1;
7795
0
        }
7796
7797
127k
        if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
7798
10.2k
        {
7799
            // Child window can be out of sight and have "negative" clip windows.
7800
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7801
10.2k
            IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0 || window->DockIsActive);
7802
10.2k
            const bool nav_request = (window->ChildFlags & ImGuiChildFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7803
10.2k
            if (!g.LogEnabled && !nav_request)
7804
10.2k
                if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7805
10.1k
                {
7806
10.1k
                    if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7807
0
                        window->HiddenFramesCannotSkipItems = 1;
7808
10.1k
                    else
7809
10.1k
                        window->HiddenFramesCanSkipItems = 1;
7810
10.1k
                }
7811
7812
            // Hide along with parent or if parent is collapsed
7813
10.2k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7814
0
                window->HiddenFramesCanSkipItems = 1;
7815
10.2k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7816
1
                window->HiddenFramesCannotSkipItems = 1;
7817
10.2k
        }
7818
7819
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7820
127k
        if (style.Alpha <= 0.0f)
7821
0
            window->HiddenFramesCanSkipItems = 1;
7822
7823
        // Update the Hidden flag
7824
127k
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7825
127k
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7826
7827
        // Disable inputs for requested number of frames
7828
127k
        if (window->DisableInputsFrames > 0)
7829
0
        {
7830
0
            window->DisableInputsFrames--;
7831
0
            window->Flags |= ImGuiWindowFlags_NoInputs;
7832
0
        }
7833
7834
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7835
127k
        bool skip_items = false;
7836
127k
        if (window->Collapsed || !window->Active || hidden_regular)
7837
58.3k
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7838
58.3k
                skip_items = true;
7839
127k
        window->SkipItems = skip_items;
7840
7841
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7842
127k
        if (window->SkipItems)
7843
58.3k
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7844
7845
        // Sanity check: there are two spots which can set Appearing = true
7846
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7847
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7848
127k
        if (window->SkipItems && !window->Appearing)
7849
127k
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7850
127k
    }
7851
0
    else if (first_begin_of_the_frame)
7852
0
    {
7853
        // Skip refresh mode
7854
0
        window->SkipItems = true;
7855
0
    }
7856
7857
    // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7858
    // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7859
127k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7860
127k
    if (!window->IsFallbackWindow)
7861
68.7k
        if ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size))
7862
0
        {
7863
0
            if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7864
0
            if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7865
0
            return false;
7866
0
        }
7867
127k
#endif
7868
7869
127k
    return !window->SkipItems;
7870
127k
}
7871
7872
static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect)
7873
127k
{
7874
127k
    ImGuiContext& g = *GImGui;
7875
127k
    if (window->DockIsActive)
7876
0
        SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7877
127k
    else
7878
127k
        SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(rect.Min, rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, rect);
7879
127k
}
7880
7881
void ImGui::End()
7882
127k
{
7883
127k
    ImGuiContext& g = *GImGui;
7884
127k
    ImGuiWindow* window = g.CurrentWindow;
7885
7886
    // Error checking: verify that user hasn't called End() too many times!
7887
127k
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7888
0
    {
7889
0
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7890
0
        return;
7891
0
    }
7892
127k
    ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
7893
7894
    // Error checking: verify that user doesn't directly call End() on a child window.
7895
127k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7896
127k
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7897
7898
    // Close anything that is open
7899
127k
    if (window->DC.CurrentColumns)
7900
0
        EndColumns();
7901
127k
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh)   // Pop inner window clip rectangle
7902
127k
        PopClipRect();
7903
127k
    PopFocusScope();
7904
127k
    if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
7905
0
        EndDisabledOverrideReenable();
7906
7907
127k
    if (window->SkipRefresh)
7908
0
    {
7909
0
        IM_ASSERT(window->DrawList == NULL);
7910
0
        window->DrawList = &window->DrawListInst;
7911
0
    }
7912
7913
    // Stop logging
7914
127k
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7915
116k
        LogFinish();
7916
7917
127k
    if (window->DC.IsSetPos)
7918
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7919
7920
    // Docking: report contents sizes to parent to allow for auto-resize
7921
127k
    if (window->DockNode && window->DockTabIsVisible)
7922
0
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7923
0
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7924
7925
    // Pop from window stack
7926
127k
    g.LastItemData = window_stack_data.ParentLastItemDataBackup;
7927
127k
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7928
0
        g.BeginMenuDepth--;
7929
127k
    if (window->Flags & ImGuiWindowFlags_Popup)
7930
0
        g.BeginPopupStack.pop_back();
7931
127k
    window_stack_data.StackSizesOnBegin.CompareWithContextState(&g);
7932
127k
    g.CurrentWindowStack.pop_back();
7933
127k
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7934
127k
    if (g.CurrentWindow)
7935
68.7k
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7936
127k
}
7937
7938
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7939
3.21k
{
7940
3.21k
    ImGuiContext& g = *GImGui;
7941
3.21k
    IM_ASSERT(window == window->RootWindow);
7942
7943
3.21k
    const int cur_order = window->FocusOrder;
7944
3.21k
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7945
3.21k
    if (g.WindowsFocusOrder.back() == window)
7946
3.21k
        return;
7947
7948
0
    const int new_order = g.WindowsFocusOrder.Size - 1;
7949
0
    for (int n = cur_order; n < new_order; n++)
7950
0
    {
7951
0
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7952
0
        g.WindowsFocusOrder[n]->FocusOrder--;
7953
0
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7954
0
    }
7955
0
    g.WindowsFocusOrder[new_order] = window;
7956
0
    window->FocusOrder = (short)new_order;
7957
0
}
7958
7959
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7960
3.21k
{
7961
3.21k
    ImGuiContext& g = *GImGui;
7962
3.21k
    ImGuiWindow* current_front_window = g.Windows.back();
7963
3.21k
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7964
3.21k
        return;
7965
0
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7966
0
        if (g.Windows[i] == window)
7967
0
        {
7968
0
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7969
0
            g.Windows[g.Windows.Size - 1] = window;
7970
0
            break;
7971
0
        }
7972
0
}
7973
7974
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7975
0
{
7976
0
    ImGuiContext& g = *GImGui;
7977
0
    if (g.Windows[0] == window)
7978
0
        return;
7979
0
    for (int i = 0; i < g.Windows.Size; i++)
7980
0
        if (g.Windows[i] == window)
7981
0
        {
7982
0
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7983
0
            g.Windows[0] = window;
7984
0
            break;
7985
0
        }
7986
0
}
7987
7988
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7989
0
{
7990
0
    IM_ASSERT(window != NULL && behind_window != NULL);
7991
0
    ImGuiContext& g = *GImGui;
7992
0
    window = window->RootWindow;
7993
0
    behind_window = behind_window->RootWindow;
7994
0
    int pos_wnd = FindWindowDisplayIndex(window);
7995
0
    int pos_beh = FindWindowDisplayIndex(behind_window);
7996
0
    if (pos_wnd < pos_beh)
7997
0
    {
7998
0
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7999
0
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
8000
0
        g.Windows[pos_beh - 1] = window;
8001
0
    }
8002
0
    else
8003
0
    {
8004
0
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
8005
0
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
8006
0
        g.Windows[pos_beh] = window;
8007
0
    }
8008
0
}
8009
8010
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
8011
0
{
8012
0
    ImGuiContext& g = *GImGui;
8013
0
    return g.Windows.index_from_ptr(g.Windows.find(window));
8014
0
}
8015
8016
// Moving window to front of display and set focus (which happens to be back of our sorted list)
8017
void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
8018
12.0k
{
8019
12.0k
    ImGuiContext& g = *GImGui;
8020
8021
    // Modal check?
8022
12.0k
    if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
8023
44
        if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
8024
0
        {
8025
            // This block would typically be reached in two situations:
8026
            // - API call to FocusWindow() with a window under a modal and ImGuiFocusRequestFlags_UnlessBelowModal flag.
8027
            // - User clicking on void or anything behind a modal while a modal is open (window == NULL)
8028
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
8029
0
            if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
8030
0
                BringWindowToDisplayBehind(window, blocking_modal); // Still bring right under modal. (FIXME: Could move in focus list too?)
8031
0
            ClosePopupsOverWindow(GetTopMostPopupModal(), false); // Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals
8032
0
            return;
8033
0
        }
8034
8035
    // Find last focused child (if any) and focus it instead.
8036
12.0k
    if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
8037
0
        window = NavRestoreLastChildNavWindow(window);
8038
8039
    // Apply focus
8040
12.0k
    if (g.NavWindow != window)
8041
4.56k
    {
8042
4.56k
        SetNavWindow(window);
8043
4.56k
        if (window && g.NavDisableMouseHover)
8044
559
            g.NavMousePosDirty = true;
8045
4.56k
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
8046
4.56k
        g.NavLayer = ImGuiNavLayer_Main;
8047
4.56k
        SetNavFocusScope(window ? window->NavRootFocusScopeId : 0);
8048
4.56k
        g.NavIdIsAlive = false;
8049
4.56k
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
8050
8051
        // Close popups if any
8052
4.56k
        ClosePopupsOverWindow(window, false);
8053
4.56k
    }
8054
8055
    // Move the root window to the top of the pile
8056
12.0k
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
8057
12.0k
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
8058
12.0k
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
8059
12.0k
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
8060
12.0k
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
8061
8062
    // Steal active widgets. Some of the cases it triggers includes:
8063
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
8064
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
8065
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
8066
12.0k
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
8067
156
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
8068
12
            ClearActiveID();
8069
8070
    // Passing NULL allow to disable keyboard focus
8071
12.0k
    if (!window)
8072
8.80k
        return;
8073
3.21k
    window->LastFrameJustFocused = g.FrameCount;
8074
8075
    // Select in dock node
8076
    // For #2304 we avoid applying focus immediately before the tabbar is visible.
8077
    //if (dock_node && dock_node->TabBar)
8078
    //    dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
8079
8080
    // Bring to front
8081
3.21k
    BringWindowToFocusFront(focus_front_window);
8082
3.21k
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
8083
3.21k
        BringWindowToDisplayFront(display_front_window);
8084
3.21k
}
8085
8086
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
8087
0
{
8088
0
    ImGuiContext& g = *GImGui;
8089
0
    int start_idx = g.WindowsFocusOrder.Size - 1;
8090
0
    if (under_this_window != NULL)
8091
0
    {
8092
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
8093
0
        int offset = -1;
8094
0
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
8095
0
        {
8096
0
            under_this_window = under_this_window->ParentWindow;
8097
0
            offset = 0;
8098
0
        }
8099
0
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
8100
0
    }
8101
0
    for (int i = start_idx; i >= 0; i--)
8102
0
    {
8103
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
8104
0
        ImGuiWindow* window = g.WindowsFocusOrder[i];
8105
0
        if (window == ignore_window || !window->WasActive)
8106
0
            continue;
8107
0
        if (filter_viewport != NULL && window->Viewport != filter_viewport)
8108
0
            continue;
8109
0
        if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
8110
0
        {
8111
            // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
8112
            // This is failing (lagging by one frame) for docked windows.
8113
            // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
8114
            // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
8115
            // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
8116
0
            FocusWindow(window, flags);
8117
0
            return;
8118
0
        }
8119
0
    }
8120
0
    FocusWindow(NULL, flags);
8121
0
}
8122
8123
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
8124
void ImGui::SetCurrentFont(ImFont* font)
8125
58.4k
{
8126
58.4k
    ImGuiContext& g = *GImGui;
8127
58.4k
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
8128
58.4k
    IM_ASSERT(font->Scale > 0.0f);
8129
58.4k
    g.Font = font;
8130
58.4k
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
8131
58.4k
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
8132
58.4k
    g.FontScale = g.FontSize / g.Font->FontSize;
8133
8134
58.4k
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
8135
58.4k
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
8136
58.4k
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
8137
58.4k
    g.DrawListSharedData.Font = g.Font;
8138
58.4k
    g.DrawListSharedData.FontSize = g.FontSize;
8139
58.4k
    g.DrawListSharedData.FontScale = g.FontScale;
8140
58.4k
}
8141
8142
void ImGui::PushFont(ImFont* font)
8143
0
{
8144
0
    ImGuiContext& g = *GImGui;
8145
0
    if (!font)
8146
0
        font = GetDefaultFont();
8147
0
    SetCurrentFont(font);
8148
0
    g.FontStack.push_back(font);
8149
0
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
8150
0
}
8151
8152
void  ImGui::PopFont()
8153
0
{
8154
0
    ImGuiContext& g = *GImGui;
8155
0
    g.CurrentWindow->DrawList->PopTextureID();
8156
0
    g.FontStack.pop_back();
8157
0
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
8158
0
}
8159
8160
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
8161
10.2k
{
8162
10.2k
    ImGuiContext& g = *GImGui;
8163
10.2k
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
8164
10.2k
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
8165
10.2k
    if (enabled)
8166
10.2k
        item_flags |= option;
8167
0
    else
8168
0
        item_flags &= ~option;
8169
10.2k
    g.CurrentItemFlags = item_flags;
8170
10.2k
    g.ItemFlagsStack.push_back(item_flags);
8171
10.2k
}
8172
8173
void ImGui::PopItemFlag()
8174
10.2k
{
8175
10.2k
    ImGuiContext& g = *GImGui;
8176
10.2k
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
8177
10.2k
    g.ItemFlagsStack.pop_back();
8178
10.2k
    g.CurrentItemFlags = g.ItemFlagsStack.back();
8179
10.2k
}
8180
8181
// BeginDisabled()/EndDisabled()
8182
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
8183
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
8184
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
8185
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
8186
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
8187
void ImGui::BeginDisabled(bool disabled)
8188
0
{
8189
0
    ImGuiContext& g = *GImGui;
8190
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8191
0
    if (!was_disabled && disabled)
8192
0
    {
8193
0
        g.DisabledAlphaBackup = g.Style.Alpha;
8194
0
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
8195
0
    }
8196
0
    if (was_disabled || disabled)
8197
0
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
8198
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags); // FIXME-OPT: can we simply skip this and use DisabledStackSize?
8199
0
    g.DisabledStackSize++;
8200
0
}
8201
8202
void ImGui::EndDisabled()
8203
0
{
8204
0
    ImGuiContext& g = *GImGui;
8205
0
    IM_ASSERT(g.DisabledStackSize > 0);
8206
0
    g.DisabledStackSize--;
8207
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8208
    //PopItemFlag();
8209
0
    g.ItemFlagsStack.pop_back();
8210
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
8211
0
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
8212
0
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
8213
0
}
8214
8215
// Could have been called BeginDisabledDisable() but it didn't want to be award nominated for most awkward function name.
8216
// Ideally we would use a shared e.g. BeginDisabled()->BeginDisabledEx() but earlier needs to be optimal.
8217
// The whole code for this is awkward, will reevaluate if we find a way to implement SetNextItemDisabled().
8218
void ImGui::BeginDisabledOverrideReenable()
8219
0
{
8220
0
    ImGuiContext& g = *GImGui;
8221
0
    IM_ASSERT(g.CurrentItemFlags & ImGuiItemFlags_Disabled);
8222
0
    g.Style.Alpha = g.DisabledAlphaBackup;
8223
0
    g.CurrentItemFlags &= ~ImGuiItemFlags_Disabled;
8224
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
8225
0
    g.DisabledStackSize++;
8226
0
}
8227
8228
void ImGui::EndDisabledOverrideReenable()
8229
0
{
8230
0
    ImGuiContext& g = *GImGui;
8231
0
    g.DisabledStackSize--;
8232
0
    IM_ASSERT(g.DisabledStackSize > 0);
8233
0
    g.ItemFlagsStack.pop_back();
8234
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
8235
0
    g.Style.Alpha = g.DisabledAlphaBackup * g.Style.DisabledAlpha;
8236
0
}
8237
8238
void ImGui::PushTextWrapPos(float wrap_pos_x)
8239
0
{
8240
0
    ImGuiWindow* window = GetCurrentWindow();
8241
0
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
8242
0
    window->DC.TextWrapPos = wrap_pos_x;
8243
0
}
8244
8245
void ImGui::PopTextWrapPos()
8246
0
{
8247
0
    ImGuiWindow* window = GetCurrentWindow();
8248
0
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
8249
0
    window->DC.TextWrapPosStack.pop_back();
8250
0
}
8251
8252
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
8253
0
{
8254
0
    ImGuiWindow* last_window = NULL;
8255
0
    while (last_window != window)
8256
0
    {
8257
0
        last_window = window;
8258
0
        window = window->RootWindow;
8259
0
        if (popup_hierarchy)
8260
0
            window = window->RootWindowPopupTree;
8261
0
    if (dock_hierarchy)
8262
0
      window = window->RootWindowDockTree;
8263
0
  }
8264
0
    return window;
8265
0
}
8266
8267
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
8268
0
{
8269
0
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
8270
0
    if (window_root == potential_parent)
8271
0
        return true;
8272
0
    while (window != NULL)
8273
0
    {
8274
0
        if (window == potential_parent)
8275
0
            return true;
8276
0
        if (window == window_root) // end of chain
8277
0
            return false;
8278
0
        window = window->ParentWindow;
8279
0
    }
8280
0
    return false;
8281
0
}
8282
8283
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
8284
0
{
8285
0
    if (window->RootWindow == potential_parent)
8286
0
        return true;
8287
0
    while (window != NULL)
8288
0
    {
8289
0
        if (window == potential_parent)
8290
0
            return true;
8291
0
        window = window->ParentWindowInBeginStack;
8292
0
    }
8293
0
    return false;
8294
0
}
8295
8296
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
8297
0
{
8298
0
    ImGuiContext& g = *GImGui;
8299
8300
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
8301
0
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
8302
0
    if (display_layer_delta != 0)
8303
0
        return display_layer_delta > 0;
8304
8305
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
8306
0
    {
8307
0
        ImGuiWindow* candidate_window = g.Windows[i];
8308
0
        if (candidate_window == potential_above)
8309
0
            return true;
8310
0
        if (candidate_window == potential_below)
8311
0
            return false;
8312
0
    }
8313
0
    return false;
8314
0
}
8315
8316
// Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options.
8317
// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
8318
// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
8319
// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
8320
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
8321
13.4k
{
8322
13.4k
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0 && "Invalid flags for IsWindowHovered()!");
8323
8324
13.4k
    ImGuiContext& g = *GImGui;
8325
13.4k
    ImGuiWindow* ref_window = g.HoveredWindow;
8326
13.4k
    ImGuiWindow* cur_window = g.CurrentWindow;
8327
13.4k
    if (ref_window == NULL)
8328
13.3k
        return false;
8329
8330
64
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
8331
64
    {
8332
64
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
8333
64
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
8334
64
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
8335
64
        if (flags & ImGuiHoveredFlags_RootWindow)
8336
0
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8337
8338
64
        bool result;
8339
64
        if (flags & ImGuiHoveredFlags_ChildWindows)
8340
0
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8341
64
        else
8342
64
            result = (ref_window == cur_window);
8343
64
        if (!result)
8344
63
            return false;
8345
64
    }
8346
8347
1
    if (!IsWindowContentHoverable(ref_window, flags))
8348
0
        return false;
8349
1
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
8350
1
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
8351
0
            return false;
8352
8353
    // When changing hovered window we requires a bit of stationary delay before activating hover timer.
8354
    // FIXME: We don't support delay other than stationary one for now, other delay would need a way
8355
    // to fulfill the possibility that multiple IsWindowHovered() with varying flag could return true
8356
    // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
8357
    // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
8358
1
    if (flags & ImGuiHoveredFlags_ForTooltip)
8359
0
        flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
8360
1
    if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
8361
0
        return false;
8362
8363
1
    return true;
8364
1
}
8365
8366
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
8367
20.1k
{
8368
20.1k
    ImGuiContext& g = *GImGui;
8369
20.1k
    ImGuiWindow* ref_window = g.NavWindow;
8370
20.1k
    ImGuiWindow* cur_window = g.CurrentWindow;
8371
8372
20.1k
    if (ref_window == NULL)
8373
13.0k
        return false;
8374
7.12k
    if (flags & ImGuiFocusedFlags_AnyWindow)
8375
0
        return true;
8376
8377
7.12k
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
8378
7.12k
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
8379
7.12k
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
8380
7.12k
    if (flags & ImGuiHoveredFlags_RootWindow)
8381
0
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8382
8383
7.12k
    if (flags & ImGuiHoveredFlags_ChildWindows)
8384
0
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8385
7.12k
    else
8386
7.12k
        return (ref_window == cur_window);
8387
7.12k
}
8388
8389
ImGuiID ImGui::GetWindowDockID()
8390
0
{
8391
0
    ImGuiContext& g = *GImGui;
8392
0
    return g.CurrentWindow->DockId;
8393
0
}
8394
8395
bool ImGui::IsWindowDocked()
8396
0
{
8397
0
    ImGuiContext& g = *GImGui;
8398
0
    return g.CurrentWindow->DockIsActive;
8399
0
}
8400
8401
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
8402
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
8403
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
8404
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
8405
0
{
8406
0
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
8407
0
}
8408
8409
float ImGui::GetWindowWidth()
8410
2.96k
{
8411
2.96k
    ImGuiWindow* window = GImGui->CurrentWindow;
8412
2.96k
    return window->Size.x;
8413
2.96k
}
8414
8415
float ImGui::GetWindowHeight()
8416
2.97k
{
8417
2.97k
    ImGuiWindow* window = GImGui->CurrentWindow;
8418
2.97k
    return window->Size.y;
8419
2.97k
}
8420
8421
ImVec2 ImGui::GetWindowPos()
8422
0
{
8423
0
    ImGuiContext& g = *GImGui;
8424
0
    ImGuiWindow* window = g.CurrentWindow;
8425
0
    return window->Pos;
8426
0
}
8427
8428
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8429
53
{
8430
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8431
53
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8432
0
        return;
8433
8434
53
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8435
53
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8436
53
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8437
8438
    // Set
8439
53
    const ImVec2 old_pos = window->Pos;
8440
53
    window->Pos = ImTrunc(pos);
8441
53
    ImVec2 offset = window->Pos - old_pos;
8442
53
    if (offset.x == 0.0f && offset.y == 0.0f)
8443
0
        return;
8444
53
    MarkIniSettingsDirty(window);
8445
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
8446
53
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
8447
53
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8448
53
    window->DC.IdealMaxPos += offset;
8449
53
    window->DC.CursorStartPos += offset;
8450
53
}
8451
8452
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8453
0
{
8454
0
    ImGuiWindow* window = GetCurrentWindowRead();
8455
0
    SetWindowPos(window, pos, cond);
8456
0
}
8457
8458
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8459
0
{
8460
0
    if (ImGuiWindow* window = FindWindowByName(name))
8461
0
        SetWindowPos(window, pos, cond);
8462
0
}
8463
8464
ImVec2 ImGui::GetWindowSize()
8465
0
{
8466
0
    ImGuiWindow* window = GetCurrentWindowRead();
8467
0
    return window->Size;
8468
0
}
8469
8470
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8471
68.7k
{
8472
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8473
68.7k
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8474
58.4k
        return;
8475
8476
10.2k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8477
10.2k
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8478
8479
    // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize)
8480
10.2k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8481
2
        window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8482
10.2k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8483
2
        window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8484
8485
    // Set
8486
10.2k
    ImVec2 old_size = window->SizeFull;
8487
10.2k
    if (size.x <= 0.0f)
8488
0
        window->AutoFitOnlyGrows = false;
8489
10.2k
    else
8490
10.2k
        window->SizeFull.x = IM_TRUNC(size.x);
8491
10.2k
    if (size.y <= 0.0f)
8492
1
        window->AutoFitOnlyGrows = false;
8493
10.2k
    else
8494
10.2k
        window->SizeFull.y = IM_TRUNC(size.y);
8495
10.2k
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8496
10.1k
        MarkIniSettingsDirty(window);
8497
10.2k
}
8498
8499
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8500
0
{
8501
0
    SetWindowSize(GImGui->CurrentWindow, size, cond);
8502
0
}
8503
8504
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8505
0
{
8506
0
    if (ImGuiWindow* window = FindWindowByName(name))
8507
0
        SetWindowSize(window, size, cond);
8508
0
}
8509
8510
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8511
0
{
8512
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8513
0
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8514
0
        return;
8515
0
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8516
8517
    // Set
8518
0
    window->Collapsed = collapsed;
8519
0
}
8520
8521
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8522
0
{
8523
0
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
8524
0
    window->HitTestHoleSize = ImVec2ih(size);
8525
0
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8526
0
}
8527
8528
void ImGui::SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8529
0
{
8530
0
    window->Hidden = window->SkipItems = true;
8531
0
    window->HiddenFramesCanSkipItems = 1;
8532
0
}
8533
8534
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8535
0
{
8536
0
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
8537
0
}
8538
8539
bool ImGui::IsWindowCollapsed()
8540
0
{
8541
0
    ImGuiWindow* window = GetCurrentWindowRead();
8542
0
    return window->Collapsed;
8543
0
}
8544
8545
bool ImGui::IsWindowAppearing()
8546
0
{
8547
0
    ImGuiWindow* window = GetCurrentWindowRead();
8548
0
    return window->Appearing;
8549
0
}
8550
8551
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8552
0
{
8553
0
    if (ImGuiWindow* window = FindWindowByName(name))
8554
0
        SetWindowCollapsed(window, collapsed, cond);
8555
0
}
8556
8557
void ImGui::SetWindowFocus()
8558
2.96k
{
8559
2.96k
    FocusWindow(GImGui->CurrentWindow);
8560
2.96k
}
8561
8562
void ImGui::SetWindowFocus(const char* name)
8563
0
{
8564
0
    if (name)
8565
0
    {
8566
0
        if (ImGuiWindow* window = FindWindowByName(name))
8567
0
            FocusWindow(window);
8568
0
    }
8569
0
    else
8570
0
    {
8571
0
        FocusWindow(NULL);
8572
0
    }
8573
0
}
8574
8575
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8576
0
{
8577
0
    ImGuiContext& g = *GImGui;
8578
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8579
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
8580
0
    g.NextWindowData.PosVal = pos;
8581
0
    g.NextWindowData.PosPivotVal = pivot;
8582
0
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8583
0
    g.NextWindowData.PosUndock = true;
8584
0
}
8585
8586
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
8587
68.7k
{
8588
68.7k
    ImGuiContext& g = *GImGui;
8589
68.7k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8590
68.7k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
8591
68.7k
    g.NextWindowData.SizeVal = size;
8592
68.7k
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8593
68.7k
}
8594
8595
// For each axis:
8596
// - Use 0.0f as min or FLT_MAX as max if you don't want limits, e.g. size_min = (500.0f, 0.0f), size_max = (FLT_MAX, FLT_MAX) sets a minimum width.
8597
// - Use -1 for both min and max of same axis to preserve current size which itself is a constraint.
8598
// - See "Demo->Examples->Constrained-resizing window" for examples.
8599
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8600
0
{
8601
0
    ImGuiContext& g = *GImGui;
8602
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8603
0
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8604
0
    g.NextWindowData.SizeCallback = custom_callback;
8605
0
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8606
0
}
8607
8608
// Content size = inner scrollable rectangle, padded with WindowPadding.
8609
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8610
void ImGui::SetNextWindowContentSize(const ImVec2& size)
8611
0
{
8612
0
    ImGuiContext& g = *GImGui;
8613
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8614
0
    g.NextWindowData.ContentSizeVal = ImTrunc(size);
8615
0
}
8616
8617
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8618
0
{
8619
0
    ImGuiContext& g = *GImGui;
8620
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8621
0
    g.NextWindowData.ScrollVal = scroll;
8622
0
}
8623
8624
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8625
0
{
8626
0
    ImGuiContext& g = *GImGui;
8627
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8628
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8629
0
    g.NextWindowData.CollapsedVal = collapsed;
8630
0
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8631
0
}
8632
8633
void ImGui::SetNextWindowFocus()
8634
0
{
8635
0
    ImGuiContext& g = *GImGui;
8636
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8637
0
}
8638
8639
void ImGui::SetNextWindowBgAlpha(float alpha)
8640
0
{
8641
0
    ImGuiContext& g = *GImGui;
8642
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8643
0
    g.NextWindowData.BgAlphaVal = alpha;
8644
0
}
8645
8646
void ImGui::SetNextWindowViewport(ImGuiID id)
8647
0
{
8648
0
    ImGuiContext& g = *GImGui;
8649
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
8650
0
    g.NextWindowData.ViewportId = id;
8651
0
}
8652
8653
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
8654
0
{
8655
0
    ImGuiContext& g = *GImGui;
8656
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
8657
0
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
8658
0
    g.NextWindowData.DockId = id;
8659
0
}
8660
8661
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
8662
0
{
8663
0
    ImGuiContext& g = *GImGui;
8664
0
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
8665
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
8666
0
    g.NextWindowData.WindowClass = *window_class;
8667
0
}
8668
8669
// This is experimental and meant to be a toy for exploring a future/wider range of features.
8670
void ImGui::SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags)
8671
0
{
8672
0
    ImGuiContext& g = *GImGui;
8673
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasRefreshPolicy;
8674
0
    g.NextWindowData.RefreshFlagsVal = flags;
8675
0
}
8676
8677
ImDrawList* ImGui::GetWindowDrawList()
8678
10.2k
{
8679
10.2k
    ImGuiWindow* window = GetCurrentWindow();
8680
10.2k
    return window->DrawList;
8681
10.2k
}
8682
8683
float ImGui::GetWindowDpiScale()
8684
0
{
8685
0
    ImGuiContext& g = *GImGui;
8686
0
    return g.CurrentDpiScale;
8687
0
}
8688
8689
ImGuiViewport* ImGui::GetWindowViewport()
8690
0
{
8691
0
    ImGuiContext& g = *GImGui;
8692
0
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
8693
0
    return g.CurrentViewport;
8694
0
}
8695
8696
ImFont* ImGui::GetFont()
8697
894k
{
8698
894k
    return GImGui->Font;
8699
894k
}
8700
8701
float ImGui::GetFontSize()
8702
894k
{
8703
894k
    return GImGui->FontSize;
8704
894k
}
8705
8706
ImVec2 ImGui::GetFontTexUvWhitePixel()
8707
0
{
8708
0
    return GImGui->DrawListSharedData.TexUvWhitePixel;
8709
0
}
8710
8711
void ImGui::SetWindowFontScale(float scale)
8712
0
{
8713
0
    IM_ASSERT(scale > 0.0f);
8714
0
    ImGuiContext& g = *GImGui;
8715
0
    ImGuiWindow* window = GetCurrentWindow();
8716
0
    window->FontWindowScale = scale;
8717
0
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8718
0
    g.FontScale = g.DrawListSharedData.FontScale = g.FontSize / g.Font->FontSize;
8719
0
}
8720
8721
void ImGui::PushFocusScope(ImGuiID id)
8722
127k
{
8723
127k
    ImGuiContext& g = *GImGui;
8724
127k
    ImGuiFocusScopeData data;
8725
127k
    data.ID = id;
8726
127k
    data.WindowID = g.CurrentWindow->ID;
8727
127k
    g.FocusScopeStack.push_back(data);
8728
127k
    g.CurrentFocusScopeId = id;
8729
127k
}
8730
8731
void ImGui::PopFocusScope()
8732
127k
{
8733
127k
    ImGuiContext& g = *GImGui;
8734
127k
    if (g.FocusScopeStack.Size == 0)
8735
0
    {
8736
0
        IM_ASSERT_USER_ERROR(g.FocusScopeStack.Size > 0, "Calling PopFocusScope() too many times!");
8737
0
        return;
8738
0
    }
8739
127k
    g.FocusScopeStack.pop_back();
8740
127k
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back().ID : 0;
8741
127k
}
8742
8743
void ImGui::SetNavFocusScope(ImGuiID focus_scope_id)
8744
5.04k
{
8745
5.04k
    ImGuiContext& g = *GImGui;
8746
5.04k
    g.NavFocusScopeId = focus_scope_id;
8747
5.04k
    g.NavFocusRoute.resize(0); // Invalidate
8748
5.04k
    if (focus_scope_id == 0)
8749
2.27k
        return;
8750
2.77k
    IM_ASSERT(g.NavWindow != NULL);
8751
8752
    // Store current path (in reverse order)
8753
2.77k
    if (focus_scope_id == g.CurrentFocusScopeId)
8754
2.40k
    {
8755
        // Top of focus stack contains local focus scopes inside current window
8756
4.81k
        for (int n = g.FocusScopeStack.Size - 1; n >= 0 && g.FocusScopeStack.Data[n].WindowID == g.CurrentWindow->ID; n--)
8757
2.40k
            g.NavFocusRoute.push_back(g.FocusScopeStack.Data[n]);
8758
2.40k
    }
8759
363
    else if (focus_scope_id == g.NavWindow->NavRootFocusScopeId)
8760
353
        g.NavFocusRoute.push_back({ focus_scope_id, g.NavWindow->ID });
8761
10
    else
8762
10
        return;
8763
8764
    // Then follow on manually set ParentWindowForFocusRoute field (#6798)
8765
4.94k
    for (ImGuiWindow* window = g.NavWindow->ParentWindowForFocusRoute; window != NULL; window = window->ParentWindowForFocusRoute)
8766
2.18k
        g.NavFocusRoute.push_back({ window->NavRootFocusScopeId, window->ID });
8767
2.76k
    IM_ASSERT(g.NavFocusRoute.Size < 100); // Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3
8768
2.76k
}
8769
8770
// Focus = move navigation cursor, set scrolling, set focus window.
8771
void ImGui::FocusItem()
8772
0
{
8773
0
    ImGuiContext& g = *GImGui;
8774
0
    ImGuiWindow* window = g.CurrentWindow;
8775
0
    IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
8776
0
    if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
8777
0
    {
8778
0
        IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
8779
0
        return;
8780
0
    }
8781
8782
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight | ImGuiNavMoveFlags_NoSelect;
8783
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8784
0
    SetNavWindow(window);
8785
0
    NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
8786
0
    NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8787
0
}
8788
8789
void ImGui::ActivateItemByID(ImGuiID id)
8790
0
{
8791
0
    ImGuiContext& g = *GImGui;
8792
0
    g.NavNextActivateId = id;
8793
0
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
8794
0
}
8795
8796
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8797
// But ActivateItem() should function without altering scroll/focus?
8798
void ImGui::SetKeyboardFocusHere(int offset)
8799
0
{
8800
0
    ImGuiContext& g = *GImGui;
8801
0
    ImGuiWindow* window = g.CurrentWindow;
8802
0
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
8803
0
    IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8804
8805
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8806
    // When we refactor this function into ActivateItem() we may want to make this an option.
8807
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8808
    // is also automatically dropped in the event g.ActiveId is stolen.
8809
0
    if (g.DragDropActive || g.MovingWindow != NULL)
8810
0
    {
8811
0
        IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8812
0
        return;
8813
0
    }
8814
8815
0
    SetNavWindow(window);
8816
8817
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight;
8818
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8819
0
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8820
0
    if (offset == -1)
8821
0
    {
8822
0
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8823
0
    }
8824
0
    else
8825
0
    {
8826
0
        g.NavTabbingDir = 1;
8827
0
        g.NavTabbingCounter = offset + 1;
8828
0
    }
8829
0
}
8830
8831
void ImGui::SetItemDefaultFocus()
8832
0
{
8833
0
    ImGuiContext& g = *GImGui;
8834
0
    ImGuiWindow* window = g.CurrentWindow;
8835
0
    if (!window->Appearing)
8836
0
        return;
8837
0
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8838
0
        return;
8839
8840
0
    g.NavInitRequest = false;
8841
0
    NavApplyItemToResult(&g.NavInitResult);
8842
0
    NavUpdateAnyRequestFlag();
8843
8844
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8845
0
    if (!window->ClipRect.Contains(g.LastItemData.Rect))
8846
0
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8847
0
}
8848
8849
void ImGui::SetStateStorage(ImGuiStorage* tree)
8850
0
{
8851
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8852
0
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8853
0
}
8854
8855
ImGuiStorage* ImGui::GetStateStorage()
8856
0
{
8857
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8858
0
    return window->DC.StateStorage;
8859
0
}
8860
8861
bool ImGui::IsRectVisible(const ImVec2& size)
8862
0
{
8863
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8864
0
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8865
0
}
8866
8867
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8868
0
{
8869
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8870
0
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8871
0
}
8872
8873
//-----------------------------------------------------------------------------
8874
// [SECTION] ID STACK
8875
//-----------------------------------------------------------------------------
8876
8877
// This is one of the very rare legacy case where we use ImGuiWindow methods,
8878
// it should ideally be flattened at some point but it's been used a lots by widgets.
8879
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
8880
157k
{
8881
157k
    ImGuiID seed = IDStack.back();
8882
157k
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8883
157k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8884
157k
    ImGuiContext& g = *Ctx;
8885
157k
    if (g.DebugHookIdInfo == id)
8886
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8887
157k
#endif
8888
157k
    return id;
8889
157k
}
8890
8891
ImGuiID ImGuiWindow::GetID(const void* ptr)
8892
0
{
8893
0
    ImGuiID seed = IDStack.back();
8894
0
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
8895
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8896
0
    ImGuiContext& g = *Ctx;
8897
0
    if (g.DebugHookIdInfo == id)
8898
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
8899
0
#endif
8900
0
    return id;
8901
0
}
8902
8903
ImGuiID ImGuiWindow::GetID(int n)
8904
61.3k
{
8905
61.3k
    ImGuiID seed = IDStack.back();
8906
61.3k
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8907
61.3k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8908
61.3k
    ImGuiContext& g = *Ctx;
8909
61.3k
    if (g.DebugHookIdInfo == id)
8910
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8911
61.3k
#endif
8912
61.3k
    return id;
8913
61.3k
}
8914
8915
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
8916
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
8917
0
{
8918
0
    ImGuiID seed = IDStack.back();
8919
0
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
8920
0
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
8921
0
    return id;
8922
0
}
8923
8924
void ImGui::PushID(const char* str_id)
8925
10.2k
{
8926
10.2k
    ImGuiContext& g = *GImGui;
8927
10.2k
    ImGuiWindow* window = g.CurrentWindow;
8928
10.2k
    ImGuiID id = window->GetID(str_id);
8929
10.2k
    window->IDStack.push_back(id);
8930
10.2k
}
8931
8932
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8933
0
{
8934
0
    ImGuiContext& g = *GImGui;
8935
0
    ImGuiWindow* window = g.CurrentWindow;
8936
0
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8937
0
    window->IDStack.push_back(id);
8938
0
}
8939
8940
void ImGui::PushID(const void* ptr_id)
8941
0
{
8942
0
    ImGuiContext& g = *GImGui;
8943
0
    ImGuiWindow* window = g.CurrentWindow;
8944
0
    ImGuiID id = window->GetID(ptr_id);
8945
0
    window->IDStack.push_back(id);
8946
0
}
8947
8948
void ImGui::PushID(int int_id)
8949
0
{
8950
0
    ImGuiContext& g = *GImGui;
8951
0
    ImGuiWindow* window = g.CurrentWindow;
8952
0
    ImGuiID id = window->GetID(int_id);
8953
0
    window->IDStack.push_back(id);
8954
0
}
8955
8956
// Push a given id value ignoring the ID stack as a seed.
8957
void ImGui::PushOverrideID(ImGuiID id)
8958
0
{
8959
0
    ImGuiContext& g = *GImGui;
8960
0
    ImGuiWindow* window = g.CurrentWindow;
8961
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8962
0
    if (g.DebugHookIdInfo == id)
8963
0
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8964
0
#endif
8965
0
    window->IDStack.push_back(id);
8966
0
}
8967
8968
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8969
// (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
8970
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8971
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8972
0
{
8973
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8974
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8975
0
    ImGuiContext& g = *GImGui;
8976
0
    if (g.DebugHookIdInfo == id)
8977
0
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8978
0
#endif
8979
0
    return id;
8980
0
}
8981
8982
ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8983
0
{
8984
0
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8985
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8986
0
    ImGuiContext& g = *GImGui;
8987
0
    if (g.DebugHookIdInfo == id)
8988
0
        DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8989
0
#endif
8990
0
    return id;
8991
0
}
8992
8993
void ImGui::PopID()
8994
10.2k
{
8995
10.2k
    ImGuiWindow* window = GImGui->CurrentWindow;
8996
10.2k
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8997
10.2k
    window->IDStack.pop_back();
8998
10.2k
}
8999
9000
ImGuiID ImGui::GetID(const char* str_id)
9001
0
{
9002
0
    ImGuiWindow* window = GImGui->CurrentWindow;
9003
0
    return window->GetID(str_id);
9004
0
}
9005
9006
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
9007
0
{
9008
0
    ImGuiWindow* window = GImGui->CurrentWindow;
9009
0
    return window->GetID(str_id_begin, str_id_end);
9010
0
}
9011
9012
ImGuiID ImGui::GetID(const void* ptr_id)
9013
0
{
9014
0
    ImGuiWindow* window = GImGui->CurrentWindow;
9015
0
    return window->GetID(ptr_id);
9016
0
}
9017
9018
//-----------------------------------------------------------------------------
9019
// [SECTION] INPUTS
9020
//-----------------------------------------------------------------------------
9021
// - GetModForModKey() [Internal]
9022
// - FixupKeyChord() [Internal]
9023
// - GetKeyData() [Internal]
9024
// - GetKeyIndex() [Internal]
9025
// - GetKeyName()
9026
// - GetKeyChordName() [Internal]
9027
// - CalcTypematicRepeatAmount() [Internal]
9028
// - GetTypematicRepeatRate() [Internal]
9029
// - GetKeyPressedAmount() [Internal]
9030
// - GetKeyMagnitude2d() [Internal]
9031
//-----------------------------------------------------------------------------
9032
// - UpdateKeyRoutingTable() [Internal]
9033
// - GetRoutingIdFromOwnerId() [Internal]
9034
// - GetShortcutRoutingData() [Internal]
9035
// - CalcRoutingScore() [Internal]
9036
// - SetShortcutRouting() [Internal]
9037
// - TestShortcutRouting() [Internal]
9038
//-----------------------------------------------------------------------------
9039
// - IsKeyDown()
9040
// - IsKeyPressed()
9041
// - IsKeyReleased()
9042
//-----------------------------------------------------------------------------
9043
// - IsMouseDown()
9044
// - IsMouseClicked()
9045
// - IsMouseReleased()
9046
// - IsMouseDoubleClicked()
9047
// - GetMouseClickedCount()
9048
// - IsMouseHoveringRect() [Internal]
9049
// - IsMouseDragPastThreshold() [Internal]
9050
// - IsMouseDragging()
9051
// - GetMousePos()
9052
// - SetMousePos() [Internal]
9053
// - GetMousePosOnOpeningCurrentPopup()
9054
// - IsMousePosValid()
9055
// - IsAnyMouseDown()
9056
// - GetMouseDragDelta()
9057
// - ResetMouseDragDelta()
9058
// - GetMouseCursor()
9059
// - SetMouseCursor()
9060
//-----------------------------------------------------------------------------
9061
// - UpdateAliasKey()
9062
// - GetMergedModsFromKeys()
9063
// - UpdateKeyboardInputs()
9064
// - UpdateMouseInputs()
9065
//-----------------------------------------------------------------------------
9066
// - LockWheelingWindow [Internal]
9067
// - FindBestWheelingWindow [Internal]
9068
// - UpdateMouseWheel() [Internal]
9069
//-----------------------------------------------------------------------------
9070
// - SetNextFrameWantCaptureKeyboard()
9071
// - SetNextFrameWantCaptureMouse()
9072
//-----------------------------------------------------------------------------
9073
// - GetInputSourceName() [Internal]
9074
// - DebugPrintInputEvent() [Internal]
9075
// - UpdateInputEvents() [Internal]
9076
//-----------------------------------------------------------------------------
9077
// - GetKeyOwner() [Internal]
9078
// - TestKeyOwner() [Internal]
9079
// - SetKeyOwner() [Internal]
9080
// - SetItemKeyOwner() [Internal]
9081
// - Shortcut() [Internal]
9082
//-----------------------------------------------------------------------------
9083
9084
static ImGuiKeyChord GetModForModKey(ImGuiKey key)
9085
0
{
9086
0
    if (key == ImGuiKey_LeftCtrl || key == ImGuiKey_RightCtrl)
9087
0
        return ImGuiMod_Ctrl;
9088
0
    if (key == ImGuiKey_LeftShift || key == ImGuiKey_RightShift)
9089
0
        return ImGuiMod_Shift;
9090
0
    if (key == ImGuiKey_LeftAlt || key == ImGuiKey_RightAlt)
9091
0
        return ImGuiMod_Alt;
9092
0
    if (key == ImGuiKey_LeftSuper || key == ImGuiKey_RightSuper)
9093
0
        return ImGuiMod_Super;
9094
0
    return ImGuiMod_None;
9095
0
}
9096
9097
ImGuiKeyChord ImGui::FixupKeyChord(ImGuiKeyChord key_chord)
9098
233k
{
9099
    // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9100
233k
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9101
233k
    if (IsModKey(key))
9102
0
        key_chord |= GetModForModKey(key);
9103
233k
    return key_chord;
9104
233k
}
9105
9106
ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
9107
1.55M
{
9108
1.55M
    ImGuiContext& g = *ctx;
9109
9110
    // Special storage location for mods
9111
1.55M
    if (key & ImGuiMod_Mask_)
9112
467k
        key = ConvertSingleModFlagToKey(key);
9113
9114
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9115
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
9116
    if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
9117
        key = (ImGuiKey)g.IO.KeyMap[key];  // Remap native->imgui or imgui->native
9118
#else
9119
1.55M
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
9120
1.55M
#endif
9121
1.55M
    return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
9122
1.55M
}
9123
9124
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9125
// Formally moved to obsolete section in 1.90.5 in spite of documented as obsolete since 1.87
9126
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
9127
{
9128
    ImGuiContext& g = *GImGui;
9129
    IM_ASSERT(IsNamedKey(key));
9130
    const ImGuiKeyData* key_data = GetKeyData(key);
9131
    return (ImGuiKey)(key_data - g.IO.KeysData);
9132
}
9133
#endif
9134
9135
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
9136
static const char* const GKeyNames[] =
9137
{
9138
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
9139
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
9140
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
9141
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
9142
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
9143
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
9144
    "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
9145
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
9146
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
9147
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
9148
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
9149
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
9150
    "AppBack", "AppForward",
9151
    "GamepadStart", "GamepadBack",
9152
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
9153
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
9154
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
9155
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
9156
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
9157
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
9158
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
9159
};
9160
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
9161
9162
const char* ImGui::GetKeyName(ImGuiKey key)
9163
0
{
9164
0
    if (key == ImGuiKey_None)
9165
0
        return "None";
9166
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
9167
0
    IM_ASSERT(IsNamedKeyOrMod(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
9168
#else
9169
    ImGuiContext& g = *GImGui;
9170
    if (IsLegacyKey(key))
9171
    {
9172
        if (g.IO.KeyMap[key] == -1)
9173
            return "N/A";
9174
        IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
9175
        key = (ImGuiKey)g.IO.KeyMap[key];
9176
    }
9177
#endif
9178
0
    if (key & ImGuiMod_Mask_)
9179
0
        key = ConvertSingleModFlagToKey(key);
9180
0
    if (!IsNamedKey(key))
9181
0
        return "Unknown";
9182
9183
0
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
9184
0
}
9185
9186
// Return untranslated names: on macOS, Cmd key will show as Ctrl, Ctrl key will show as super.
9187
// Lifetime of return value: valid until next call to same function.
9188
const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord)
9189
0
{
9190
0
    ImGuiContext& g = *GImGui;
9191
9192
0
    const ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9193
0
    if (IsModKey(key))
9194
0
        key_chord &= ~GetModForModKey(key); // Return "Ctrl+LeftShift" instead of "Ctrl+Shift+LeftShift"
9195
0
    ImFormatString(g.TempKeychordName, IM_ARRAYSIZE(g.TempKeychordName), "%s%s%s%s%s",
9196
0
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
9197
0
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
9198
0
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
9199
0
        (key_chord & ImGuiMod_Super) ? "Super+" : "",
9200
0
        (key != ImGuiKey_None || key_chord == ImGuiKey_None) ? GetKeyName(key) : "");
9201
0
    size_t len;
9202
0
    if (key == ImGuiKey_None && key_chord != 0)
9203
0
        if ((len = strlen(g.TempKeychordName)) != 0) // Remove trailing '+'
9204
0
            g.TempKeychordName[len - 1] = 0;
9205
0
    return g.TempKeychordName;
9206
0
}
9207
9208
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
9209
// t1 = current time (e.g.: g.Time)
9210
// An event is triggered at:
9211
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
9212
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
9213
44
{
9214
44
    if (t1 == 0.0f)
9215
0
        return 1;
9216
44
    if (t0 >= t1)
9217
0
        return 0;
9218
44
    if (repeat_rate <= 0.0f)
9219
0
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
9220
44
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
9221
44
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
9222
44
    const int count = count_t1 - count_t0;
9223
44
    return count;
9224
44
}
9225
9226
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
9227
1.82k
{
9228
1.82k
    ImGuiContext& g = *GImGui;
9229
1.82k
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
9230
1.82k
    {
9231
385
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
9232
0
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
9233
1.44k
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
9234
1.82k
    }
9235
1.82k
}
9236
9237
// Return value representing the number of presses in the last time period, for the given repeat rate
9238
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
9239
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
9240
44
{
9241
44
    ImGuiContext& g = *GImGui;
9242
44
    const ImGuiKeyData* key_data = GetKeyData(key);
9243
44
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9244
0
        return 0;
9245
44
    const float t = key_data->DownDuration;
9246
44
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
9247
44
}
9248
9249
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
9250
ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
9251
0
{
9252
0
    return ImVec2(
9253
0
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
9254
0
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
9255
0
}
9256
9257
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
9258
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
9259
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
9260
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
9261
static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
9262
58.4k
{
9263
58.4k
    ImGuiContext& g = *GImGui;
9264
58.4k
    rt->EntriesNext.resize(0);
9265
9.06M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9266
9.00M
    {
9267
9.00M
        const int new_routing_start_idx = rt->EntriesNext.Size;
9268
9.00M
        ImGuiKeyRoutingData* routing_entry;
9269
9.00M
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
9270
0
        {
9271
0
            routing_entry = &rt->Entries[old_routing_idx];
9272
0
            routing_entry->RoutingCurrScore = routing_entry->RoutingNextScore;
9273
0
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
9274
0
            routing_entry->RoutingNext = ImGuiKeyOwner_NoOwner;
9275
0
            routing_entry->RoutingNextScore = 255;
9276
0
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_NoOwner)
9277
0
                continue;
9278
0
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
9279
9280
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
9281
            // This is the result of previous frame's SetShortcutRouting() call.
9282
0
            if (routing_entry->Mods == g.IO.KeyMods)
9283
0
            {
9284
0
                ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9285
0
                if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
9286
0
                {
9287
0
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
9288
                    //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr);
9289
0
                }
9290
0
            }
9291
0
        }
9292
9293
        // Rewrite linked-list
9294
9.00M
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
9295
9.00M
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
9296
0
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
9297
9.00M
    }
9298
58.4k
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
9299
58.4k
}
9300
9301
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
9302
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
9303
0
{
9304
0
    ImGuiContext& g = *GImGui;
9305
0
    return (owner_id != ImGuiKeyOwner_NoOwner && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
9306
0
}
9307
9308
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
9309
0
{
9310
    // Majority of shortcuts will be Key + any number of Mods
9311
    // We accept _Single_ mod with ImGuiKey_None.
9312
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
9313
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
9314
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
9315
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
9316
0
    ImGuiContext& g = *GImGui;
9317
0
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
9318
0
    ImGuiKeyRoutingData* routing_data;
9319
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9320
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9321
0
    if (key == ImGuiKey_None)
9322
0
        key = ConvertSingleModFlagToKey(mods);
9323
0
    IM_ASSERT(IsNamedKey(key));
9324
9325
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
9326
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
9327
0
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
9328
0
    {
9329
0
        routing_data = &rt->Entries[idx];
9330
0
        if (routing_data->Mods == mods)
9331
0
            return routing_data;
9332
0
    }
9333
9334
    // Add to linked-list
9335
0
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
9336
0
    rt->Entries.push_back(ImGuiKeyRoutingData());
9337
0
    routing_data = &rt->Entries[routing_data_idx];
9338
0
    routing_data->Mods = (ImU16)mods;
9339
0
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
9340
0
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
9341
0
    return routing_data;
9342
0
}
9343
9344
// Current score encoding (lower is highest priority):
9345
//  -   0: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverActive
9346
//  -   1: ImGuiInputFlags_ActiveItem or ImGuiInputFlags_RouteFocused (if item active)
9347
//  -   2: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused
9348
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
9349
//  - 254: ImGuiInputFlags_RouteGlobal
9350
//  - 255: never route
9351
// 'flags' should include an explicit routing policy
9352
static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInputFlags flags)
9353
0
{
9354
0
    ImGuiContext& g = *GImGui;
9355
0
    if (flags & ImGuiInputFlags_RouteFocused)
9356
0
    {
9357
        // ActiveID gets top priority
9358
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
9359
0
        if (owner_id != 0 && g.ActiveId == owner_id)
9360
0
            return 1;
9361
9362
        // Score based on distance to focused window (lower is better)
9363
        // Assuming both windows are submitting a routing request,
9364
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
9365
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
9366
        // Assuming only WindowA is submitting a routing request,
9367
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
9368
        // This essentially follow the window->ParentWindowForFocusRoute chain.
9369
0
        if (focus_scope_id == 0)
9370
0
            return 255;
9371
0
        for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++)
9372
0
            if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id)
9373
0
                return 3 + index_in_focus_path;
9374
0
        return 255;
9375
0
    }
9376
0
    else if (flags & ImGuiInputFlags_RouteActive)
9377
0
    {
9378
0
        if (owner_id != 0 && g.ActiveId == owner_id)
9379
0
            return 1;
9380
0
        return 255;
9381
0
    }
9382
0
    else if (flags & ImGuiInputFlags_RouteGlobal)
9383
0
    {
9384
0
        if (flags & ImGuiInputFlags_RouteOverActive)
9385
0
            return 0;
9386
0
        if (flags & ImGuiInputFlags_RouteOverFocused)
9387
0
            return 2;
9388
0
        return 254;
9389
0
    }
9390
0
    IM_ASSERT(0);
9391
0
    return 0;
9392
0
}
9393
9394
// We need this to filter some Shortcut() routes when an item e.g. an InputText() is active
9395
// e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be.
9396
static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord)
9397
0
{
9398
    // Mimic 'ignore_char_inputs' logic in InputText()
9399
0
    ImGuiContext& g = *GImGui;
9400
9401
    // When the right mods are pressed it cannot be a char input so we won't filter the shortcut out.
9402
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9403
0
    const bool ignore_char_inputs = ((mods & ImGuiMod_Ctrl) && !(mods & ImGuiMod_Alt)) || (g.IO.ConfigMacOSXBehaviors && (mods & ImGuiMod_Ctrl));
9404
0
    if (ignore_char_inputs)
9405
0
        return false;
9406
9407
    // Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered.
9408
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9409
0
    return g.KeysMayBeCharInput.TestBit(key);
9410
0
}
9411
9412
// Request a desired route for an input chord (key + mods).
9413
// Return true if the route is available this frame.
9414
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
9415
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
9416
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
9417
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
9418
116k
{
9419
116k
    ImGuiContext& g = *GImGui;
9420
116k
    if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
9421
0
        flags |= ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
9422
116k
    else
9423
116k
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteTypeMask_)); // Check that only 1 routing flag is used
9424
116k
    IM_ASSERT(owner_id != ImGuiKeyOwner_Any && owner_id != ImGuiKeyOwner_NoOwner);
9425
116k
    if (flags & (ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive | ImGuiInputFlags_RouteUnlessBgFocused))
9426
116k
        IM_ASSERT(flags & ImGuiInputFlags_RouteGlobal);
9427
9428
    // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9429
116k
    key_chord = FixupKeyChord(key_chord);
9430
9431
    // [DEBUG] Debug break requested by user
9432
116k
    if (g.DebugBreakInShortcutRouting == key_chord)
9433
0
        IM_DEBUG_BREAK();
9434
9435
116k
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
9436
0
        if (g.NavWindow == NULL)
9437
0
            return false;
9438
9439
    // Note how ImGuiInputFlags_RouteAlways won't set routing and thus won't set owner. May want to rework this?
9440
116k
    if (flags & ImGuiInputFlags_RouteAlways)
9441
116k
    {
9442
116k
        IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> always, no register\n", GetKeyChordName(key_chord), flags, owner_id);
9443
116k
        return true;
9444
116k
    }
9445
9446
    // Specific culling when there's an active item.
9447
0
    if (g.ActiveId != 0 && g.ActiveId != owner_id)
9448
0
    {
9449
0
        if (flags & ImGuiInputFlags_RouteActive)
9450
0
            return false;
9451
9452
        // Cull shortcuts with no modifiers when it could generate a character.
9453
        // e.g. Shortcut(ImGuiKey_G) also generates 'g' character, should not trigger when InputText() is active.
9454
        // but  Shortcut(Ctrl+G) should generally trigger when InputText() is active.
9455
        // TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active.
9456
        // (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined)
9457
0
        if (g.IO.WantTextInput && IsKeyChordPotentiallyCharInput(key_chord))
9458
0
        {
9459
0
            IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> filtered as potential char input\n", GetKeyChordName(key_chord), flags, owner_id);
9460
0
            return false;
9461
0
        }
9462
9463
        // ActiveIdUsingAllKeyboardKeys trumps all for ActiveId
9464
0
        if ((flags & ImGuiInputFlags_RouteOverActive) == 0 && g.ActiveIdUsingAllKeyboardKeys)
9465
0
        {
9466
0
            ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9467
0
            if (key == ImGuiKey_None)
9468
0
                key = ConvertSingleModFlagToKey((ImGuiKey)(key_chord & ImGuiMod_Mask_));
9469
0
            if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9470
0
                return false;
9471
0
        }
9472
0
    }
9473
9474
    // Where do we evaluate route for?
9475
0
    ImGuiID focus_scope_id = g.CurrentFocusScopeId;
9476
0
    if (flags & ImGuiInputFlags_RouteFromRootWindow)
9477
0
        focus_scope_id = g.CurrentWindow->RootWindow->ID; // See PushFocusScope() call in Begin()
9478
9479
0
    const int score = CalcRoutingScore(focus_scope_id, owner_id, flags);
9480
0
    IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> score %d\n", GetKeyChordName(key_chord), flags, owner_id, score);
9481
0
    if (score == 255)
9482
0
        return false;
9483
9484
    // Submit routing for NEXT frame (assuming score is sufficient)
9485
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
9486
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
9487
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
9488
0
    if (score < routing_data->RoutingNextScore)
9489
0
    {
9490
0
        routing_data->RoutingNext = owner_id;
9491
0
        routing_data->RoutingNextScore = (ImU8)score;
9492
0
    }
9493
9494
    // Return routing state for CURRENT frame
9495
0
    if (routing_data->RoutingCurr == owner_id)
9496
0
        IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route\n");
9497
0
    return routing_data->RoutingCurr == owner_id;
9498
0
}
9499
9500
// Currently unused by core (but used by tests)
9501
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
9502
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
9503
0
{
9504
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
9505
0
    key_chord = FixupKeyChord(key_chord);
9506
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
9507
0
    return routing_data->RoutingCurr == routing_id;
9508
0
}
9509
9510
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
9511
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
9512
bool ImGui::IsKeyDown(ImGuiKey key)
9513
880k
{
9514
880k
    return IsKeyDown(key, ImGuiKeyOwner_Any);
9515
880k
}
9516
9517
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
9518
888k
{
9519
888k
    const ImGuiKeyData* key_data = GetKeyData(key);
9520
888k
    if (!key_data->Down)
9521
857k
        return false;
9522
31.0k
    if (!TestKeyOwner(key, owner_id))
9523
0
        return false;
9524
31.0k
    return true;
9525
31.0k
}
9526
9527
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
9528
44.0k
{
9529
44.0k
    return IsKeyPressed(key, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
9530
44.0k
}
9531
9532
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
9533
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id)
9534
244k
{
9535
244k
    const ImGuiKeyData* key_data = GetKeyData(key);
9536
244k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9537
236k
        return false;
9538
7.87k
    const float t = key_data->DownDuration;
9539
7.87k
    if (t < 0.0f)
9540
0
        return false;
9541
7.87k
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
9542
7.87k
    if (flags & (ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_)) // Setting any _RepeatXXX option enables _Repeat
9543
416
        flags |= ImGuiInputFlags_Repeat;
9544
9545
7.87k
    bool pressed = (t == 0.0f);
9546
7.87k
    if (!pressed && (flags & ImGuiInputFlags_Repeat) != 0)
9547
1.82k
    {
9548
1.82k
        float repeat_delay, repeat_rate;
9549
1.82k
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
9550
1.82k
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
9551
1.82k
        if (pressed && (flags & ImGuiInputFlags_RepeatUntilMask_))
9552
0
        {
9553
            // Slightly bias 'key_pressed_time' as DownDuration is an accumulation of DeltaTime which we compare to an absolute time value.
9554
            // Ideally we'd replace DownDuration with KeyPressedTime but it would break user's code.
9555
0
            ImGuiContext& g = *GImGui;
9556
0
            double key_pressed_time = g.Time - t + 0.00001f;
9557
0
            if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChange) && (g.LastKeyModsChangeTime > key_pressed_time))
9558
0
                pressed = false;
9559
0
            if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone) && (g.LastKeyModsChangeFromNoneTime > key_pressed_time))
9560
0
                pressed = false;
9561
0
            if ((flags & ImGuiInputFlags_RepeatUntilOtherKeyPress) && (g.LastKeyboardKeyPressTime > key_pressed_time))
9562
0
                pressed = false;
9563
0
        }
9564
1.82k
    }
9565
7.87k
    if (!pressed)
9566
6.21k
        return false;
9567
1.66k
    if (!TestKeyOwner(key, owner_id))
9568
2
        return false;
9569
1.65k
    return true;
9570
1.66k
}
9571
9572
bool ImGui::IsKeyReleased(ImGuiKey key)
9573
3.13k
{
9574
3.13k
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
9575
3.13k
}
9576
9577
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
9578
3.13k
{
9579
3.13k
    const ImGuiKeyData* key_data = GetKeyData(key);
9580
3.13k
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
9581
2.63k
        return false;
9582
498
    if (!TestKeyOwner(key, owner_id))
9583
0
        return false;
9584
498
    return true;
9585
498
}
9586
9587
bool ImGui::IsMouseDown(ImGuiMouseButton button)
9588
0
{
9589
0
    ImGuiContext& g = *GImGui;
9590
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9591
0
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
9592
0
}
9593
9594
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
9595
0
{
9596
0
    ImGuiContext& g = *GImGui;
9597
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9598
0
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
9599
0
}
9600
9601
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
9602
2
{
9603
2
    return IsMouseClicked(button, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
9604
2
}
9605
9606
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id)
9607
11
{
9608
11
    ImGuiContext& g = *GImGui;
9609
11
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9610
11
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9611
10
        return false;
9612
1
    const float t = g.IO.MouseDownDuration[button];
9613
1
    if (t < 0.0f)
9614
0
        return false;
9615
1
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsMouseClicked) == 0); // Passing flags not supported by this function! // FIXME: Could support RepeatRate and RepeatUntil flags here.
9616
9617
1
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
9618
1
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
9619
1
    if (!pressed)
9620
1
        return false;
9621
9622
0
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
9623
0
        return false;
9624
9625
0
    return true;
9626
0
}
9627
9628
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
9629
0
{
9630
0
    ImGuiContext& g = *GImGui;
9631
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9632
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
9633
0
}
9634
9635
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
9636
9
{
9637
9
    ImGuiContext& g = *GImGui;
9638
9
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9639
9
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
9640
9
}
9641
9642
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
9643
1
{
9644
1
    ImGuiContext& g = *GImGui;
9645
1
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9646
1
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
9647
1
}
9648
9649
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id)
9650
0
{
9651
0
    ImGuiContext& g = *GImGui;
9652
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9653
0
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), owner_id);
9654
0
}
9655
9656
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
9657
0
{
9658
0
    ImGuiContext& g = *GImGui;
9659
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9660
0
    return g.IO.MouseClickedCount[button];
9661
0
}
9662
9663
// Test if mouse cursor is hovering given rectangle
9664
// NB- Rectangle is clipped by our current clip setting
9665
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
9666
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
9667
276k
{
9668
276k
    ImGuiContext& g = *GImGui;
9669
9670
    // Clip
9671
276k
    ImRect rect_clipped(r_min, r_max);
9672
276k
    if (clip)
9673
149k
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
9674
9675
    // Hit testing, expanded for touch input
9676
276k
    if (!rect_clipped.ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding))
9677
273k
        return false;
9678
2.52k
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
9679
37
        return false;
9680
2.48k
    return true;
9681
2.52k
}
9682
9683
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
9684
// [Internal] This doesn't test if the button is pressed
9685
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
9686
92
{
9687
92
    ImGuiContext& g = *GImGui;
9688
92
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9689
92
    if (lock_threshold < 0.0f)
9690
92
        lock_threshold = g.IO.MouseDragThreshold;
9691
92
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
9692
92
}
9693
9694
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
9695
93
{
9696
93
    ImGuiContext& g = *GImGui;
9697
93
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9698
93
    if (!g.IO.MouseDown[button])
9699
1
        return false;
9700
92
    return IsMouseDragPastThreshold(button, lock_threshold);
9701
93
}
9702
9703
ImVec2 ImGui::GetMousePos()
9704
8.22k
{
9705
8.22k
    ImGuiContext& g = *GImGui;
9706
8.22k
    return g.IO.MousePos;
9707
8.22k
}
9708
9709
// This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
9710
// It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
9711
void ImGui::TeleportMousePos(const ImVec2& pos)
9712
0
{
9713
0
    ImGuiContext& g = *GImGui;
9714
0
    g.IO.MousePos = g.IO.MousePosPrev = pos;
9715
0
    g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
9716
0
    g.IO.WantSetMousePos = true;
9717
    //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
9718
0
}
9719
9720
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
9721
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
9722
0
{
9723
0
    ImGuiContext& g = *GImGui;
9724
0
    if (g.BeginPopupStack.Size > 0)
9725
0
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
9726
0
    return g.IO.MousePos;
9727
0
}
9728
9729
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
9730
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
9731
252k
{
9732
    // The assert is only to silence a false-positive in XCode Static Analysis.
9733
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
9734
252k
    IM_ASSERT(GImGui != NULL);
9735
252k
    const float MOUSE_INVALID = -256000.0f;
9736
252k
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
9737
252k
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
9738
252k
}
9739
9740
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
9741
bool ImGui::IsAnyMouseDown()
9742
0
{
9743
0
    ImGuiContext& g = *GImGui;
9744
0
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
9745
0
        if (g.IO.MouseDown[n])
9746
0
            return true;
9747
0
    return false;
9748
0
}
9749
9750
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
9751
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
9752
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
9753
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
9754
0
{
9755
0
    ImGuiContext& g = *GImGui;
9756
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9757
0
    if (lock_threshold < 0.0f)
9758
0
        lock_threshold = g.IO.MouseDragThreshold;
9759
0
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
9760
0
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
9761
0
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
9762
0
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
9763
0
    return ImVec2(0.0f, 0.0f);
9764
0
}
9765
9766
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
9767
0
{
9768
0
    ImGuiContext& g = *GImGui;
9769
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9770
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
9771
0
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
9772
0
}
9773
9774
// Get desired mouse cursor shape.
9775
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
9776
// updated during the frame, and locked in EndFrame()/Render().
9777
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
9778
ImGuiMouseCursor ImGui::GetMouseCursor()
9779
0
{
9780
0
    ImGuiContext& g = *GImGui;
9781
0
    return g.MouseCursor;
9782
0
}
9783
9784
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
9785
0
{
9786
0
    ImGuiContext& g = *GImGui;
9787
0
    g.MouseCursor = cursor_type;
9788
0
}
9789
9790
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
9791
409k
{
9792
409k
    IM_ASSERT(ImGui::IsAliasKey(key));
9793
409k
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
9794
409k
    key_data->Down = v;
9795
409k
    key_data->AnalogValue = analog_value;
9796
409k
}
9797
9798
// [Internal] Do not use directly
9799
static ImGuiKeyChord GetMergedModsFromKeys()
9800
116k
{
9801
116k
    ImGuiKeyChord mods = 0;
9802
116k
    if (ImGui::IsKeyDown(ImGuiMod_Ctrl))     { mods |= ImGuiMod_Ctrl; }
9803
116k
    if (ImGui::IsKeyDown(ImGuiMod_Shift))    { mods |= ImGuiMod_Shift; }
9804
116k
    if (ImGui::IsKeyDown(ImGuiMod_Alt))      { mods |= ImGuiMod_Alt; }
9805
116k
    if (ImGui::IsKeyDown(ImGuiMod_Super))    { mods |= ImGuiMod_Super; }
9806
116k
    return mods;
9807
116k
}
9808
9809
static void ImGui::UpdateKeyboardInputs()
9810
58.4k
{
9811
58.4k
    ImGuiContext& g = *GImGui;
9812
58.4k
    ImGuiIO& io = g.IO;
9813
9814
58.4k
    if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
9815
0
        io.ClearInputKeys();
9816
9817
    // Import legacy keys or verify they are not used
9818
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9819
    if (io.BackendUsingLegacyKeyArrays == 0)
9820
    {
9821
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
9822
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
9823
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
9824
    }
9825
    else
9826
    {
9827
        if (g.FrameCount == 0)
9828
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9829
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
9830
9831
        // Build reverse KeyMap (Named -> Legacy)
9832
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
9833
            if (io.KeyMap[n] != -1)
9834
            {
9835
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
9836
                io.KeyMap[io.KeyMap[n]] = n;
9837
            }
9838
9839
        // Import legacy keys into new ones
9840
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9841
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
9842
            {
9843
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
9844
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
9845
                io.KeysData[key].Down = io.KeysDown[n];
9846
                if (key != n)
9847
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
9848
                io.BackendUsingLegacyKeyArrays = 1;
9849
            }
9850
        if (io.BackendUsingLegacyKeyArrays == 1)
9851
        {
9852
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
9853
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
9854
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
9855
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
9856
        }
9857
    }
9858
#endif
9859
9860
    // Import legacy ImGuiNavInput_ io inputs and convert to gamepad keys
9861
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9862
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
9863
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
9864
    {
9865
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
9866
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
9867
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
9868
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
9869
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
9870
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
9871
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
9872
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
9873
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
9874
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
9875
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
9876
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
9877
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
9878
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
9879
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
9880
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
9881
        #undef NAV_MAP_KEY
9882
    }
9883
#endif
9884
9885
    // Update aliases
9886
350k
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
9887
292k
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
9888
58.4k
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
9889
58.4k
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
9890
9891
    // Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values.
9892
    // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) ->                                      -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9893
    // - Legacy backends:      set io.KeyXXX bools               -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9894
    // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
9895
58.4k
    const ImGuiKeyChord prev_key_mods = io.KeyMods;
9896
58.4k
    io.KeyMods = GetMergedModsFromKeys();
9897
58.4k
    io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9898
58.4k
    io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9899
58.4k
    io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9900
58.4k
    io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9901
58.4k
    if (prev_key_mods != io.KeyMods)
9902
0
        g.LastKeyModsChangeTime = g.Time;
9903
58.4k
    if (prev_key_mods != io.KeyMods && prev_key_mods == 0)
9904
0
        g.LastKeyModsChangeFromNoneTime = g.Time;
9905
9906
    // Clear gamepad data if disabled
9907
58.4k
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9908
1.46M
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
9909
1.40M
        {
9910
1.40M
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
9911
1.40M
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
9912
1.40M
        }
9913
9914
    // Update keys
9915
9.06M
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
9916
9.00M
    {
9917
9.00M
        ImGuiKeyData* key_data = &io.KeysData[i];
9918
9.00M
        key_data->DownDurationPrev = key_data->DownDuration;
9919
9.00M
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9920
9.00M
        if (key_data->DownDuration == 0.0f)
9921
9.21k
        {
9922
9.21k
            ImGuiKey key = (ImGuiKey)(ImGuiKey_KeysData_OFFSET + i);
9923
9.21k
            if (IsKeyboardKey(key))
9924
3.71k
                g.LastKeyboardKeyPressTime = g.Time;
9925
5.50k
            else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper)
9926
0
                g.LastKeyboardKeyPressTime = g.Time;
9927
9.21k
        }
9928
9.00M
    }
9929
9930
    // Update keys/input owner (named keys only): one entry per key
9931
9.06M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9932
9.00M
    {
9933
9.00M
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
9934
9.00M
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9935
9.00M
        owner_data->OwnerCurr = owner_data->OwnerNext;
9936
9.00M
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
9937
8.88M
            owner_data->OwnerNext = ImGuiKeyOwner_NoOwner;
9938
9.00M
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
9939
9.00M
    }
9940
9941
    // Update key routing (for e.g. shortcuts)
9942
58.4k
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
9943
58.4k
}
9944
9945
static void ImGui::UpdateMouseInputs()
9946
58.4k
{
9947
58.4k
    ImGuiContext& g = *GImGui;
9948
58.4k
    ImGuiIO& io = g.IO;
9949
9950
    // Mouse Wheel swapping flag
9951
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9952
    // - We avoid doing it on OSX as it the OS input layer handles this already.
9953
    // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9954
    // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9955
58.4k
    io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9956
9957
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9958
58.4k
    if (IsMousePosValid(&io.MousePos))
9959
44.1k
        io.MousePos = g.MouseLastValidPos = ImFloor(io.MousePos);
9960
9961
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9962
58.4k
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
9963
43.9k
        io.MouseDelta = io.MousePos - io.MousePosPrev;
9964
14.4k
    else
9965
14.4k
        io.MouseDelta = ImVec2(0.0f, 0.0f);
9966
9967
    // Update stationary timer.
9968
    // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
9969
58.4k
    const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
9970
58.4k
    const bool mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
9971
58.4k
    g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
9972
    //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
9973
9974
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
9975
58.4k
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9976
2.66k
        g.NavDisableMouseHover = false;
9977
9978
350k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9979
292k
    {
9980
292k
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9981
292k
        io.MouseClickedCount[i] = 0; // Will be filled below
9982
292k
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9983
292k
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9984
292k
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9985
292k
        if (io.MouseClicked[i])
9986
3.58k
        {
9987
3.58k
            bool is_repeated_click = false;
9988
3.58k
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9989
3.02k
            {
9990
3.02k
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9991
3.02k
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9992
2.97k
                    is_repeated_click = true;
9993
3.02k
            }
9994
3.58k
            if (is_repeated_click)
9995
2.97k
                io.MouseClickedLastCount[i]++;
9996
609
            else
9997
609
                io.MouseClickedLastCount[i] = 1;
9998
3.58k
            io.MouseClickedTime[i] = g.Time;
9999
3.58k
            io.MouseClickedPos[i] = io.MousePos;
10000
3.58k
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
10001
3.58k
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
10002
3.58k
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
10003
3.58k
        }
10004
288k
        else if (io.MouseDown[i])
10005
77.0k
        {
10006
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
10007
77.0k
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
10008
77.0k
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
10009
77.0k
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
10010
77.0k
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
10011
77.0k
        }
10012
10013
        // We provide io.MouseDoubleClicked[] as a legacy service
10014
292k
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
10015
10016
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
10017
292k
        if (io.MouseClicked[i])
10018
3.58k
            g.NavDisableMouseHover = false;
10019
292k
    }
10020
58.4k
}
10021
10022
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
10023
0
{
10024
0
    ImGuiContext& g = *GImGui;
10025
0
    if (window)
10026
0
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
10027
0
    else
10028
0
        g.WheelingWindowReleaseTimer = 0.0f;
10029
0
    if (g.WheelingWindow == window)
10030
0
        return;
10031
0
    IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
10032
0
    g.WheelingWindow = window;
10033
0
    g.WheelingWindowRefMousePos = g.IO.MousePos;
10034
0
    if (window == NULL)
10035
0
    {
10036
0
        g.WheelingWindowStartFrame = -1;
10037
0
        g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
10038
0
    }
10039
0
}
10040
10041
static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
10042
1
{
10043
    // For each axis, find window in the hierarchy that may want to use scrolling
10044
1
    ImGuiContext& g = *GImGui;
10045
1
    ImGuiWindow* windows[2] = { NULL, NULL };
10046
3
    for (int axis = 0; axis < 2; axis++)
10047
2
        if (wheel[axis] != 0.0f)
10048
2
            for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
10049
0
            {
10050
                // Bubble up into parent window if:
10051
                // - a child window doesn't allow any scrolling.
10052
                // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
10053
                //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
10054
0
                const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
10055
0
                const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
10056
                //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
10057
0
                if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
10058
0
                    break; // select this window
10059
0
            }
10060
1
    if (windows[0] == NULL && windows[1] == NULL)
10061
0
        return NULL;
10062
10063
    // If there's only one window or only one axis then there's no ambiguity
10064
1
    if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
10065
1
        return windows[1] ? windows[1] : windows[0];
10066
10067
    // If candidate are different windows we need to decide which one to prioritize
10068
    // - First frame: only find a winner if one axis is zero.
10069
    // - Subsequent frames: only find a winner when one is more than the other.
10070
0
    if (g.WheelingWindowStartFrame == -1)
10071
0
        g.WheelingWindowStartFrame = g.FrameCount;
10072
0
    if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
10073
0
    {
10074
0
        g.WheelingWindowWheelRemainder = wheel;
10075
0
        return NULL;
10076
0
    }
10077
0
    return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
10078
0
}
10079
10080
// Called by NewFrame()
10081
void ImGui::UpdateMouseWheel()
10082
58.4k
{
10083
    // Reset the locked window if we move the mouse or after the timer elapses.
10084
    // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
10085
58.4k
    ImGuiContext& g = *GImGui;
10086
58.4k
    if (g.WheelingWindow != NULL)
10087
0
    {
10088
0
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
10089
0
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
10090
0
            g.WheelingWindowReleaseTimer = 0.0f;
10091
0
        if (g.WheelingWindowReleaseTimer <= 0.0f)
10092
0
            LockWheelingWindow(NULL, 0.0f);
10093
0
    }
10094
10095
58.4k
    ImVec2 wheel;
10096
58.4k
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheelH : 0.0f;
10097
58.4k
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheel : 0.0f;
10098
10099
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
10100
58.4k
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
10101
58.4k
    if (!mouse_window || mouse_window->Collapsed)
10102
58.4k
        return;
10103
10104
    // Zoom / Scale window
10105
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
10106
64
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
10107
0
    {
10108
0
        LockWheelingWindow(mouse_window, wheel.y);
10109
0
        ImGuiWindow* window = mouse_window;
10110
0
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
10111
0
        const float scale = new_font_scale / window->FontWindowScale;
10112
0
        window->FontWindowScale = new_font_scale;
10113
0
        if (window == window->RootWindow)
10114
0
        {
10115
0
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
10116
0
            SetWindowPos(window, window->Pos + offset, 0);
10117
0
            window->Size = ImTrunc(window->Size * scale);
10118
0
            window->SizeFull = ImTrunc(window->SizeFull * scale);
10119
0
        }
10120
0
        return;
10121
0
    }
10122
64
    if (g.IO.KeyCtrl)
10123
0
        return;
10124
10125
    // Mouse wheel scrolling
10126
    // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
10127
64
    if (g.IO.MouseWheelRequestAxisSwap)
10128
0
        wheel = ImVec2(wheel.y, 0.0f);
10129
10130
    // Maintain a rough average of moving magnitude on both axises
10131
    // FIXME: should by based on wall clock time rather than frame-counter
10132
64
    g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
10133
64
    g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
10134
10135
    // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
10136
64
    wheel += g.WheelingWindowWheelRemainder;
10137
64
    g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
10138
64
    if (wheel.x == 0.0f && wheel.y == 0.0f)
10139
63
        return;
10140
10141
    // Mouse wheel scrolling: find target and apply
10142
    // - don't renew lock if axis doesn't apply on the window.
10143
    // - select a main axis when both axises are being moved.
10144
1
    if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
10145
1
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
10146
1
        {
10147
1
            bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
10148
1
            if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
10149
0
                do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
10150
1
            if (do_scroll[ImGuiAxis_X])
10151
0
            {
10152
0
                LockWheelingWindow(window, wheel.x);
10153
0
                float max_step = window->InnerRect.GetWidth() * 0.67f;
10154
0
                float scroll_step = ImTrunc(ImMin(2 * window->CalcFontSize(), max_step));
10155
0
                SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
10156
0
                g.WheelingWindowScrolledFrame = g.FrameCount;
10157
0
            }
10158
1
            if (do_scroll[ImGuiAxis_Y])
10159
0
            {
10160
0
                LockWheelingWindow(window, wheel.y);
10161
0
                float max_step = window->InnerRect.GetHeight() * 0.67f;
10162
0
                float scroll_step = ImTrunc(ImMin(5 * window->CalcFontSize(), max_step));
10163
0
                SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
10164
0
                g.WheelingWindowScrolledFrame = g.FrameCount;
10165
0
            }
10166
1
        }
10167
1
}
10168
10169
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
10170
0
{
10171
0
    ImGuiContext& g = *GImGui;
10172
0
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
10173
0
}
10174
10175
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
10176
0
{
10177
0
    ImGuiContext& g = *GImGui;
10178
0
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
10179
0
}
10180
10181
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10182
static const char* GetInputSourceName(ImGuiInputSource source)
10183
0
{
10184
0
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" };
10185
0
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
10186
0
    return input_source_names[source];
10187
0
}
10188
static const char* GetMouseSourceName(ImGuiMouseSource source)
10189
0
{
10190
0
    const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
10191
0
    IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
10192
0
    return mouse_source_names[source];
10193
0
}
10194
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
10195
0
{
10196
0
    ImGuiContext& g = *GImGui;
10197
0
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MousePos.MouseSource)); return; }
10198
0
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseButton.MouseSource)); return; }
10199
0
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("[io] %s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
10200
0
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
10201
0
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("[io] %s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
10202
0
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
10203
0
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
10204
0
}
10205
#endif
10206
10207
// Process input queue
10208
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
10209
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
10210
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
10211
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
10212
58.4k
{
10213
58.4k
    ImGuiContext& g = *GImGui;
10214
58.4k
    ImGuiIO& io = g.IO;
10215
10216
    // Only trickle chars<>key when working with InputText()
10217
    // FIXME: InputText() could parse event trail?
10218
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
10219
58.4k
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
10220
10221
58.4k
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
10222
58.4k
    int  mouse_button_changed = 0x00;
10223
58.4k
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
10224
10225
58.4k
    int event_n = 0;
10226
82.1k
    for (; event_n < g.InputEventsQueue.Size; event_n++)
10227
32.9k
    {
10228
32.9k
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
10229
32.9k
        if (e->Type == ImGuiInputEventType_MousePos)
10230
4.03k
        {
10231
4.03k
            if (g.IO.WantSetMousePos)
10232
0
                continue;
10233
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
10234
4.03k
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
10235
4.03k
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
10236
784
                break;
10237
3.24k
            io.MousePos = event_pos;
10238
3.24k
            io.MouseSource = e->MousePos.MouseSource;
10239
3.24k
            mouse_moved = true;
10240
3.24k
        }
10241
28.8k
        else if (e->Type == ImGuiInputEventType_MouseButton)
10242
11.6k
        {
10243
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10244
11.6k
            const ImGuiMouseButton button = e->MouseButton.Button;
10245
11.6k
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
10246
11.6k
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
10247
4.47k
                break;
10248
7.14k
            if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
10249
0
                break;
10250
7.14k
            io.MouseDown[button] = e->MouseButton.Down;
10251
7.14k
            io.MouseSource = e->MouseButton.MouseSource;
10252
7.14k
            mouse_button_changed |= (1 << button);
10253
7.14k
        }
10254
17.2k
        else if (e->Type == ImGuiInputEventType_MouseWheel)
10255
2.78k
        {
10256
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
10257
2.78k
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
10258
1.05k
                break;
10259
1.73k
            io.MouseWheelH += e->MouseWheel.WheelX;
10260
1.73k
            io.MouseWheel += e->MouseWheel.WheelY;
10261
1.73k
            io.MouseSource = e->MouseWheel.MouseSource;
10262
1.73k
            mouse_wheeled = true;
10263
1.73k
        }
10264
14.4k
        else if (e->Type == ImGuiInputEventType_MouseViewport)
10265
0
        {
10266
0
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
10267
0
        }
10268
14.4k
        else if (e->Type == ImGuiInputEventType_Key)
10269
6.88k
        {
10270
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10271
6.88k
            if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10272
0
                continue;
10273
6.88k
            ImGuiKey key = e->Key.Key;
10274
6.88k
            IM_ASSERT(key != ImGuiKey_None);
10275
6.88k
            ImGuiKeyData* key_data = GetKeyData(key);
10276
6.88k
            const int key_data_index = (int)(key_data - g.IO.KeysData);
10277
6.88k
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
10278
1.40k
                break;
10279
5.48k
            key_data->Down = e->Key.Down;
10280
5.48k
            key_data->AnalogValue = e->Key.AnalogValue;
10281
5.48k
            key_changed = true;
10282
5.48k
            key_changed_mask.SetBit(key_data_index);
10283
10284
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
10285
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
10286
            io.KeysDown[key_data_index] = key_data->Down;
10287
            if (io.KeyMap[key_data_index] != -1)
10288
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
10289
#endif
10290
5.48k
        }
10291
7.58k
        else if (e->Type == ImGuiInputEventType_Text)
10292
5.06k
        {
10293
5.06k
            if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10294
0
                continue;
10295
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
10296
5.06k
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
10297
1.49k
                break;
10298
3.57k
            unsigned int c = e->Text.Char;
10299
3.57k
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
10300
3.57k
            if (trickle_interleaved_keys_and_text)
10301
0
                text_inputted = true;
10302
3.57k
        }
10303
2.52k
        else if (e->Type == ImGuiInputEventType_Focus)
10304
2.52k
        {
10305
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
10306
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
10307
2.52k
            const bool focus_lost = !e->AppFocused.Focused;
10308
2.52k
            io.AppFocusLost = focus_lost;
10309
2.52k
        }
10310
0
        else
10311
0
        {
10312
0
            IM_ASSERT(0 && "Unknown event!");
10313
0
        }
10314
32.9k
    }
10315
10316
    // Record trail (for domain-specific applications wanting to access a precise trail)
10317
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
10318
82.1k
    for (int n = 0; n < event_n; n++)
10319
23.7k
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
10320
10321
    // [DEBUG]
10322
58.4k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10323
58.4k
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
10324
0
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
10325
0
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
10326
58.4k
#endif
10327
10328
    // Remaining events will be processed on the next frame
10329
58.4k
    if (event_n == g.InputEventsQueue.Size)
10330
49.2k
        g.InputEventsQueue.resize(0);
10331
9.20k
    else
10332
9.20k
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
10333
10334
    // Clear buttons state when focus is lost
10335
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
10336
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
10337
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
10338
58.4k
    if (g.IO.AppFocusLost)
10339
2.47k
    {
10340
2.47k
        g.IO.ClearInputKeys();
10341
2.47k
        g.IO.ClearInputMouse();
10342
2.47k
    }
10343
58.4k
}
10344
10345
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
10346
0
{
10347
0
    if (!IsNamedKeyOrMod(key))
10348
0
        return ImGuiKeyOwner_NoOwner;
10349
10350
0
    ImGuiContext& g = *GImGui;
10351
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10352
0
    ImGuiID owner_id = owner_data->OwnerCurr;
10353
10354
0
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10355
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10356
0
            return ImGuiKeyOwner_NoOwner;
10357
10358
0
    return owner_id;
10359
0
}
10360
10361
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
10362
// TestKeyOwner(..., None) : (owner == None)
10363
// TestKeyOwner(..., Any)  : no owner test
10364
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
10365
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
10366
156k
{
10367
156k
    if (!IsNamedKeyOrMod(key))
10368
0
        return true;
10369
10370
156k
    ImGuiContext& g = *GImGui;
10371
156k
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10372
182
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10373
2
            return false;
10374
10375
156k
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10376
156k
    if (owner_id == ImGuiKeyOwner_Any)
10377
31.3k
        return (owner_data->LockThisFrame == false);
10378
10379
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
10380
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
10381
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
10382
125k
    if (owner_data->OwnerCurr != owner_id)
10383
0
    {
10384
0
        if (owner_data->LockThisFrame)
10385
0
            return false;
10386
0
        if (owner_data->OwnerCurr != ImGuiKeyOwner_NoOwner)
10387
0
            return false;
10388
0
    }
10389
10390
125k
    return true;
10391
125k
}
10392
10393
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
10394
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
10395
// - SetKeyOwner(..., None)              : clears owner
10396
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
10397
// - SetKeyOwner(..., Any or None, Lock) : set lock
10398
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
10399
0
{
10400
0
    ImGuiContext& g = *GImGui;
10401
0
    IM_ASSERT(IsNamedKeyOrMod(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
10402
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
10403
    //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags);
10404
10405
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10406
0
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
10407
10408
    // We cannot lock by default as it would likely break lots of legacy code.
10409
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
10410
0
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
10411
0
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
10412
0
}
10413
10414
// Rarely used helper
10415
void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10416
0
{
10417
0
    if (key_chord & ImGuiMod_Ctrl)      { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
10418
0
    if (key_chord & ImGuiMod_Shift)     { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
10419
0
    if (key_chord & ImGuiMod_Alt)       { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
10420
0
    if (key_chord & ImGuiMod_Super)     { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
10421
0
    if (key_chord & ~ImGuiMod_Mask_)    { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
10422
0
}
10423
10424
// This is more or less equivalent to:
10425
//   if (IsItemHovered() || IsItemActive())
10426
//       SetKeyOwner(key, GetItemID());
10427
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
10428
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
10429
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
10430
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
10431
0
{
10432
0
    ImGuiContext& g = *GImGui;
10433
0
    ImGuiID id = g.LastItemData.ID;
10434
0
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
10435
0
        return;
10436
0
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
10437
0
        flags |= ImGuiInputFlags_CondDefault_;
10438
0
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
10439
0
    {
10440
0
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
10441
0
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
10442
0
    }
10443
0
}
10444
10445
void ImGui::SetItemKeyOwner(ImGuiKey key)
10446
0
{
10447
0
    SetItemKeyOwner(key, ImGuiInputFlags_None);
10448
0
}
10449
10450
// This is the only public API until we expose owner_id versions of the API as replacements.
10451
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
10452
0
{
10453
0
    return IsKeyChordPressed(key_chord, ImGuiInputFlags_None, ImGuiKeyOwner_Any);
10454
0
}
10455
10456
// This is equivalent to comparing KeyMods + doing a IsKeyPressed()
10457
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
10458
116k
{
10459
116k
    ImGuiContext& g = *GImGui;
10460
116k
    key_chord = FixupKeyChord(key_chord);
10461
116k
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
10462
116k
    if (g.IO.KeyMods != mods)
10463
116k
        return false;
10464
10465
    // Special storage location for mods
10466
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10467
0
    if (key == ImGuiKey_None)
10468
0
        key = ConvertSingleModFlagToKey(mods);
10469
0
    if (!IsKeyPressed(key, (flags & ImGuiInputFlags_RepeatMask_), owner_id))
10470
0
        return false;
10471
0
    return true;
10472
0
}
10473
10474
void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
10475
0
{
10476
0
    ImGuiContext& g = *GImGui;
10477
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasShortcut;
10478
0
    g.NextItemData.Shortcut = key_chord;
10479
0
    g.NextItemData.ShortcutFlags = flags;
10480
0
}
10481
10482
// Called from within ItemAdd: at this point we can read from NextItemData and write to LastItemData
10483
void ImGui::ItemHandleShortcut(ImGuiID id)
10484
0
{
10485
0
    ImGuiContext& g = *GImGui;
10486
0
    ImGuiInputFlags flags = g.NextItemData.ShortcutFlags;
10487
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetNextItemShortcut) == 0); // Passing flags not supported by SetNextItemShortcut()!
10488
10489
0
    if (g.LastItemData.InFlags & ImGuiItemFlags_Disabled)
10490
0
        return;
10491
0
    if (flags & ImGuiInputFlags_Tooltip)
10492
0
    {
10493
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasShortcut;
10494
0
        g.LastItemData.Shortcut = g.NextItemData.Shortcut;
10495
0
    }
10496
0
    if (!Shortcut(g.NextItemData.Shortcut, flags & ImGuiInputFlags_SupportedByShortcut, id) || g.NavActivateId != 0)
10497
0
        return;
10498
10499
    // FIXME: Generalize Activation queue?
10500
0
    g.NavActivateId = id; // Will effectively disable clipping.
10501
0
    g.NavActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_FromShortcut;
10502
    //if (g.ActiveId == 0 || g.ActiveId == id)
10503
0
    g.NavActivateDownId = g.NavActivatePressedId = id;
10504
0
    NavHighlightActivated(id);
10505
0
}
10506
10507
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
10508
0
{
10509
0
    return Shortcut(key_chord, flags, ImGuiKeyOwner_Any);
10510
0
}
10511
10512
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
10513
116k
{
10514
116k
    ImGuiContext& g = *GImGui;
10515
    //IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)\n", GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id);
10516
10517
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
10518
116k
    if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
10519
0
        flags |= ImGuiInputFlags_RouteFocused;
10520
10521
    // Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
10522
    // Effectively makes Shortcut() always input-owner aware.
10523
116k
    if (owner_id == ImGuiKeyOwner_Any || owner_id == ImGuiKeyOwner_NoOwner)
10524
0
        owner_id = GetRoutingIdFromOwnerId(owner_id);
10525
10526
116k
    if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
10527
0
        return false;
10528
10529
    // Submit route
10530
116k
    if (!SetShortcutRouting(key_chord, flags, owner_id))
10531
0
        return false;
10532
10533
    // Default repeat behavior for Shortcut()
10534
    // So e.g. pressing Ctrl+W and releasing Ctrl while holding W will not trigger the W shortcut.
10535
116k
    if ((flags & ImGuiInputFlags_Repeat) != 0 && (flags & ImGuiInputFlags_RepeatUntilMask_) == 0)
10536
116k
        flags |= ImGuiInputFlags_RepeatUntilKeyModsChange;
10537
10538
116k
    if (!IsKeyChordPressed(key_chord, flags, owner_id))
10539
116k
        return false;
10540
10541
    // Claim mods during the press
10542
0
    SetKeyOwnersForKeyChord(key_chord & ImGuiMod_Mask_, owner_id);
10543
10544
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
10545
0
    return true;
10546
116k
}
10547
10548
10549
//-----------------------------------------------------------------------------
10550
// [SECTION] ERROR CHECKING
10551
//-----------------------------------------------------------------------------
10552
10553
// Verify ABI compatibility between caller code and compiled version of Dear ImGui. This helps detects some build issues.
10554
// Called by IMGUI_CHECKVERSION().
10555
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
10556
// If this triggers you have mismatched headers and compiled code versions.
10557
// - It could be because of a build issue (using new headers with old compiled code)
10558
// - It could be because of mismatched configuration #define, compilation settings, packing pragma etc.
10559
//   THE CONFIGURATION SETTINGS MENTIONED IN imconfig.h MUST BE SET FOR ALL COMPILATION UNITS INVOLVED WITH DEAR IMGUI.
10560
//   Which is why it is required you put them in your imconfig file (and NOT only before including imgui.h).
10561
//   Otherwise it is possible that different compilation units would see different structure layout.
10562
//   If you don't want to modify imconfig.h you can use the IMGUI_USER_CONFIG define to change filename.
10563
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
10564
1
{
10565
1
    bool error = false;
10566
1
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
10567
1
    if (sz_io    != sizeof(ImGuiIO))    { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
10568
1
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
10569
1
    if (sz_vec2  != sizeof(ImVec2))     { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
10570
1
    if (sz_vec4  != sizeof(ImVec4))     { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
10571
1
    if (sz_vert  != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
10572
1
    if (sz_idx   != sizeof(ImDrawIdx))  { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
10573
1
    return !error;
10574
1
}
10575
10576
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
10577
// This is causing issues and ambiguity and we need to retire that.
10578
// See https://github.com/ocornut/imgui/issues/5548 for more details.
10579
// [Scenario 1]
10580
//  Previously this would make the window content size ~200x200:
10581
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
10582
//  Instead, please submit an item:
10583
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
10584
//  Alternative:
10585
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
10586
// [Scenario 2]
10587
//  For reference this is one of the issue what we aim to fix with this change:
10588
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
10589
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
10590
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
10591
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
10592
0
{
10593
0
    ImGuiContext& g = *GImGui;
10594
0
    ImGuiWindow* window = g.CurrentWindow;
10595
0
    IM_ASSERT(window->DC.IsSetPos);
10596
0
    window->DC.IsSetPos = false;
10597
0
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
10598
0
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
10599
0
        return;
10600
0
    if (window->SkipItems)
10601
0
        return;
10602
0
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
10603
#else
10604
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10605
#endif
10606
0
}
10607
10608
static void ImGui::ErrorCheckNewFrameSanityChecks()
10609
58.4k
{
10610
58.4k
    ImGuiContext& g = *GImGui;
10611
10612
    // Check user IM_ASSERT macro
10613
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
10614
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
10615
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
10616
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
10617
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
10618
58.4k
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
10619
10620
    // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
10621
    // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
10622
#ifdef __EMSCRIPTEN__
10623
    if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
10624
        g.IO.DeltaTime = 0.00001f;
10625
#endif
10626
10627
    // Check user data
10628
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
10629
58.4k
    IM_ASSERT(g.Initialized);
10630
58.4k
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
10631
58.4k
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
10632
58.4k
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
10633
58.4k
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
10634
58.4k
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
10635
58.4k
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
10636
58.4k
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
10637
58.4k
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
10638
58.4k
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
10639
58.4k
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
10640
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
10641
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
10642
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
10643
10644
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
10645
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
10646
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
10647
#endif
10648
10649
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
10650
58.4k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
10651
58.4k
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10652
58.4k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
10653
58.4k
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10654
10655
    // Perform simple checks: multi-viewport and platform windows support
10656
58.4k
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
10657
1
    {
10658
1
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
10659
0
        {
10660
0
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
10661
0
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
10662
0
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
10663
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
10664
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
10665
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
10666
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
10667
0
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
10668
0
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
10669
0
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
10670
0
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
10671
0
        }
10672
1
        else
10673
1
        {
10674
            // Disable feature, our backends do not support it
10675
1
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
10676
1
        }
10677
10678
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
10679
1
        for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors)
10680
0
        {
10681
0
            IM_UNUSED(mon);
10682
0
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
10683
0
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
10684
0
            IM_ASSERT(mon.DpiScale != 0.0f);
10685
0
        }
10686
1
    }
10687
58.4k
}
10688
10689
static void ImGui::ErrorCheckEndFrameSanityChecks()
10690
58.4k
{
10691
58.4k
    ImGuiContext& g = *GImGui;
10692
10693
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
10694
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
10695
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
10696
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
10697
    // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
10698
    // while still correctly asserting on mid-frame key press events.
10699
58.4k
    const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
10700
58.4k
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
10701
58.4k
    IM_UNUSED(key_mods);
10702
10703
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
10704
    //ErrorCheckEndFrameRecover();
10705
10706
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
10707
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
10708
58.4k
    if (g.CurrentWindowStack.Size != 1)
10709
0
    {
10710
0
        if (g.CurrentWindowStack.Size > 1)
10711
0
        {
10712
0
            ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
10713
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
10714
0
            IM_UNUSED(window);
10715
0
            while (g.CurrentWindowStack.Size > 1)
10716
0
                End();
10717
0
        }
10718
0
        else
10719
0
        {
10720
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
10721
0
        }
10722
0
    }
10723
10724
58.4k
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
10725
58.4k
}
10726
10727
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
10728
// Must be called during or before EndFrame().
10729
// This is generally flawed as we are not necessarily End/Popping things in the right order.
10730
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
10731
// FIXME: Can't recover from interleaved BeginTabBar/Begin
10732
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10733
0
{
10734
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
10735
0
    ImGuiContext& g = *GImGui;
10736
0
    while (g.CurrentWindowStack.Size > 0) //-V1044
10737
0
    {
10738
0
        ErrorCheckEndWindowRecover(log_callback, user_data);
10739
0
        ImGuiWindow* window = g.CurrentWindow;
10740
0
        if (g.CurrentWindowStack.Size == 1)
10741
0
        {
10742
0
            IM_ASSERT(window->IsFallbackWindow);
10743
0
            break;
10744
0
        }
10745
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
10746
0
        {
10747
0
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
10748
0
            EndChild();
10749
0
        }
10750
0
        else
10751
0
        {
10752
0
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
10753
0
            End();
10754
0
        }
10755
0
    }
10756
0
}
10757
10758
// Must be called before End()/EndChild()
10759
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10760
0
{
10761
0
    ImGuiContext& g = *GImGui;
10762
0
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
10763
0
    {
10764
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
10765
0
        EndTable();
10766
0
    }
10767
10768
0
    ImGuiWindow* window = g.CurrentWindow;
10769
0
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
10770
0
    IM_ASSERT(window != NULL);
10771
0
    while (g.CurrentTabBar != NULL) //-V1044
10772
0
    {
10773
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
10774
0
        EndTabBar();
10775
0
    }
10776
0
    while (g.CurrentMultiSelect != NULL && g.CurrentMultiSelect->Storage->Window == window)
10777
0
    {
10778
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndMultiSelect() in '%s'", window->Name);
10779
0
        EndMultiSelect();
10780
0
    }
10781
0
    while (window->DC.TreeDepth > 0)
10782
0
    {
10783
0
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
10784
0
        TreePop();
10785
0
    }
10786
0
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
10787
0
    {
10788
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
10789
0
        EndGroup();
10790
0
    }
10791
0
    while (window->IDStack.Size > 1)
10792
0
    {
10793
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
10794
0
        PopID();
10795
0
    }
10796
0
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
10797
0
    {
10798
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
10799
0
        if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
10800
0
            EndDisabled();
10801
0
        else
10802
0
        {
10803
0
            EndDisabledOverrideReenable();
10804
0
            g.CurrentWindowStack.back().DisabledOverrideReenable = false;
10805
0
        }
10806
0
    }
10807
0
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
10808
0
    {
10809
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
10810
0
        PopStyleColor();
10811
0
    }
10812
0
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
10813
0
    {
10814
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
10815
0
        PopItemFlag();
10816
0
    }
10817
0
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
10818
0
    {
10819
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
10820
0
        PopStyleVar();
10821
0
    }
10822
0
    while (g.FontStack.Size > stack_sizes->SizeOfFontStack) //-V1044
10823
0
    {
10824
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'", window->Name);
10825
0
        PopFont();
10826
0
    }
10827
0
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
10828
0
    {
10829
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
10830
0
        PopFocusScope();
10831
0
    }
10832
0
}
10833
10834
// Save current stack sizes for later compare
10835
void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
10836
127k
{
10837
127k
    ImGuiContext& g = *ctx;
10838
127k
    ImGuiWindow* window = g.CurrentWindow;
10839
127k
    SizeOfIDStack = (short)window->IDStack.Size;
10840
127k
    SizeOfColorStack = (short)g.ColorStack.Size;
10841
127k
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
10842
127k
    SizeOfFontStack = (short)g.FontStack.Size;
10843
127k
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
10844
127k
    SizeOfGroupStack = (short)g.GroupStack.Size;
10845
127k
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
10846
127k
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
10847
127k
    SizeOfDisabledStack = (short)g.DisabledStackSize;
10848
127k
}
10849
10850
// Compare to detect usage errors
10851
void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
10852
127k
{
10853
127k
    ImGuiContext& g = *ctx;
10854
127k
    ImGuiWindow* window = g.CurrentWindow;
10855
127k
    IM_UNUSED(window);
10856
10857
    // Window stacks
10858
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
10859
127k
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
10860
10861
    // Global stacks
10862
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
10863
127k
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
10864
127k
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
10865
127k
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
10866
127k
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
10867
127k
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
10868
127k
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
10869
127k
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
10870
127k
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
10871
127k
}
10872
10873
//-----------------------------------------------------------------------------
10874
// [SECTION] ITEM SUBMISSION
10875
//-----------------------------------------------------------------------------
10876
// - KeepAliveID()
10877
// - ItemAdd()
10878
//-----------------------------------------------------------------------------
10879
10880
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
10881
void ImGui::KeepAliveID(ImGuiID id)
10882
195k
{
10883
195k
    ImGuiContext& g = *GImGui;
10884
195k
    if (g.ActiveId == id)
10885
182
        g.ActiveIdIsAlive = id;
10886
195k
    if (g.ActiveIdPreviousFrame == id)
10887
182
        g.ActiveIdPreviousFrameIsAlive = true;
10888
195k
}
10889
10890
// Declare item bounding box for clipping and interaction.
10891
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
10892
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
10893
// THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN)
10894
IM_MSVC_RUNTIME_CHECKS_OFF
10895
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
10896
195k
{
10897
195k
    ImGuiContext& g = *GImGui;
10898
195k
    ImGuiWindow* window = g.CurrentWindow;
10899
10900
    // Set item data
10901
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
10902
195k
    g.LastItemData.ID = id;
10903
195k
    g.LastItemData.Rect = bb;
10904
195k
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
10905
195k
    g.LastItemData.InFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
10906
195k
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
10907
    // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
10908
10909
195k
    if (id != 0)
10910
195k
    {
10911
195k
        KeepAliveID(id);
10912
10913
        // Directional navigation processing
10914
        // Runs prior to clipping early-out
10915
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
10916
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
10917
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
10918
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
10919
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
10920
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
10921
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
10922
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
10923
195k
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
10924
125k
        {
10925
            // FIMXE-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test.
10926
125k
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
10927
125k
            if (g.NavId == id || g.NavAnyRequest)
10928
815
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
10929
375
                    if (window == g.NavWindow || ((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened))
10930
375
                        NavProcessItem();
10931
125k
        }
10932
10933
195k
        if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasShortcut)
10934
0
            ItemHandleShortcut(id);
10935
195k
    }
10936
10937
    // Lightweight clear of SetNextItemXXX data.
10938
195k
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
10939
195k
    g.NextItemData.ItemFlags = ImGuiItemFlags_None;
10940
10941
#ifdef IMGUI_ENABLE_TEST_ENGINE
10942
    if (id != 0)
10943
        IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
10944
#endif
10945
10946
    // Clipping test
10947
    // (this is an inline copy of IsClippedEx() so we can reuse the is_rect_visible value, otherwise we'd do 'if (IsClippedEx(bb, id)) return false')
10948
    // g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts)
10949
195k
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
10950
195k
    if (!is_rect_visible)
10951
46.9k
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
10952
46.7k
            if (!g.ItemUnclipByLog)
10953
46.7k
                return false;
10954
10955
    // [DEBUG]
10956
148k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10957
148k
    if (id != 0)
10958
148k
    {
10959
148k
        if (id == g.DebugLocateId)
10960
0
            DebugLocateItemResolveWithLastItem();
10961
10962
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
10963
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
10964
        // READ THE FAQ: https://dearimgui.com/faq
10965
148k
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
10966
148k
    }
10967
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
10968
    //if ((g.LastItemData.InFlags & ImGuiItemFlags_NoNav) == 0)
10969
    //    window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
10970
148k
#endif
10971
10972
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
10973
148k
    if (is_rect_visible)
10974
148k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
10975
148k
    if (IsMouseHoveringRect(bb.Min, bb.Max))
10976
1.07k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
10977
148k
    return true;
10978
195k
}
10979
IM_MSVC_RUNTIME_CHECKS_RESTORE
10980
10981
//-----------------------------------------------------------------------------
10982
// [SECTION] LAYOUT
10983
//-----------------------------------------------------------------------------
10984
// - ItemSize()
10985
// - SameLine()
10986
// - GetCursorScreenPos()
10987
// - SetCursorScreenPos()
10988
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
10989
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
10990
// - GetCursorStartPos()
10991
// - Indent()
10992
// - Unindent()
10993
// - SetNextItemWidth()
10994
// - PushItemWidth()
10995
// - PushMultiItemsWidths()
10996
// - PopItemWidth()
10997
// - CalcItemWidth()
10998
// - CalcItemSize()
10999
// - GetTextLineHeight()
11000
// - GetTextLineHeightWithSpacing()
11001
// - GetFrameHeight()
11002
// - GetFrameHeightWithSpacing()
11003
// - GetContentRegionMax()
11004
// - GetContentRegionMaxAbs() [Internal]
11005
// - GetContentRegionAvail(),
11006
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
11007
// - BeginGroup()
11008
// - EndGroup()
11009
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
11010
//-----------------------------------------------------------------------------
11011
11012
// Advance cursor given item size for layout.
11013
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
11014
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
11015
// THIS IS IN THE PERFORMANCE CRITICAL PATH.
11016
IM_MSVC_RUNTIME_CHECKS_OFF
11017
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
11018
10.3k
{
11019
10.3k
    ImGuiContext& g = *GImGui;
11020
10.3k
    ImGuiWindow* window = g.CurrentWindow;
11021
10.3k
    if (window->SkipItems)
11022
0
        return;
11023
11024
    // We increase the height in this function to accommodate for baseline offset.
11025
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
11026
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
11027
10.3k
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
11028
11029
10.3k
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
11030
10.3k
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
11031
11032
    // Always align ourselves on pixel boundaries
11033
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
11034
10.3k
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
11035
10.3k
    window->DC.CursorPosPrevLine.y = line_y1;
11036
10.3k
    window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
11037
10.3k
    window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y);                       // Next line
11038
10.3k
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
11039
10.3k
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
11040
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
11041
11042
10.3k
    window->DC.PrevLineSize.y = line_height;
11043
10.3k
    window->DC.CurrLineSize.y = 0.0f;
11044
10.3k
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
11045
10.3k
    window->DC.CurrLineTextBaseOffset = 0.0f;
11046
10.3k
    window->DC.IsSameLine = window->DC.IsSetPos = false;
11047
11048
    // Horizontal layout mode
11049
10.3k
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
11050
0
        SameLine();
11051
10.3k
}
11052
IM_MSVC_RUNTIME_CHECKS_RESTORE
11053
11054
// Gets back to previous line and continue with horizontal layout
11055
//      offset_from_start_x == 0 : follow right after previous item
11056
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
11057
//      spacing_w < 0            : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
11058
//      spacing_w >= 0           : enforce spacing amount
11059
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
11060
0
{
11061
0
    ImGuiContext& g = *GImGui;
11062
0
    ImGuiWindow* window = g.CurrentWindow;
11063
0
    if (window->SkipItems)
11064
0
        return;
11065
11066
0
    if (offset_from_start_x != 0.0f)
11067
0
    {
11068
0
        if (spacing_w < 0.0f)
11069
0
            spacing_w = 0.0f;
11070
0
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
11071
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
11072
0
    }
11073
0
    else
11074
0
    {
11075
0
        if (spacing_w < 0.0f)
11076
0
            spacing_w = g.Style.ItemSpacing.x;
11077
0
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
11078
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
11079
0
    }
11080
0
    window->DC.CurrLineSize = window->DC.PrevLineSize;
11081
0
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
11082
0
    window->DC.IsSameLine = true;
11083
0
}
11084
11085
ImVec2 ImGui::GetCursorScreenPos()
11086
18.4k
{
11087
18.4k
    ImGuiWindow* window = GetCurrentWindowRead();
11088
18.4k
    return window->DC.CursorPos;
11089
18.4k
}
11090
11091
void ImGui::SetCursorScreenPos(const ImVec2& pos)
11092
0
{
11093
0
    ImGuiWindow* window = GetCurrentWindow();
11094
0
    window->DC.CursorPos = pos;
11095
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11096
0
    window->DC.IsSetPos = true;
11097
0
}
11098
11099
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
11100
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
11101
ImVec2 ImGui::GetCursorPos()
11102
0
{
11103
0
    ImGuiWindow* window = GetCurrentWindowRead();
11104
0
    return window->DC.CursorPos - window->Pos + window->Scroll;
11105
0
}
11106
11107
float ImGui::GetCursorPosX()
11108
0
{
11109
0
    ImGuiWindow* window = GetCurrentWindowRead();
11110
0
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
11111
0
}
11112
11113
float ImGui::GetCursorPosY()
11114
0
{
11115
0
    ImGuiWindow* window = GetCurrentWindowRead();
11116
0
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
11117
0
}
11118
11119
void ImGui::SetCursorPos(const ImVec2& local_pos)
11120
0
{
11121
0
    ImGuiWindow* window = GetCurrentWindow();
11122
0
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
11123
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11124
0
    window->DC.IsSetPos = true;
11125
0
}
11126
11127
void ImGui::SetCursorPosX(float x)
11128
0
{
11129
0
    ImGuiWindow* window = GetCurrentWindow();
11130
0
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
11131
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
11132
0
    window->DC.IsSetPos = true;
11133
0
}
11134
11135
void ImGui::SetCursorPosY(float y)
11136
0
{
11137
0
    ImGuiWindow* window = GetCurrentWindow();
11138
0
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
11139
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
11140
0
    window->DC.IsSetPos = true;
11141
0
}
11142
11143
ImVec2 ImGui::GetCursorStartPos()
11144
0
{
11145
0
    ImGuiWindow* window = GetCurrentWindowRead();
11146
0
    return window->DC.CursorStartPos - window->Pos;
11147
0
}
11148
11149
void ImGui::Indent(float indent_w)
11150
0
{
11151
0
    ImGuiContext& g = *GImGui;
11152
0
    ImGuiWindow* window = GetCurrentWindow();
11153
0
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
11154
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
11155
0
}
11156
11157
void ImGui::Unindent(float indent_w)
11158
0
{
11159
0
    ImGuiContext& g = *GImGui;
11160
0
    ImGuiWindow* window = GetCurrentWindow();
11161
0
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
11162
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
11163
0
}
11164
11165
// Affect large frame+labels widgets only.
11166
void ImGui::SetNextItemWidth(float item_width)
11167
0
{
11168
0
    ImGuiContext& g = *GImGui;
11169
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
11170
0
    g.NextItemData.Width = item_width;
11171
0
}
11172
11173
// FIXME: Remove the == 0.0f behavior?
11174
void ImGui::PushItemWidth(float item_width)
11175
0
{
11176
0
    ImGuiContext& g = *GImGui;
11177
0
    ImGuiWindow* window = g.CurrentWindow;
11178
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
11179
0
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
11180
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
11181
0
}
11182
11183
void ImGui::PushMultiItemsWidths(int components, float w_full)
11184
0
{
11185
0
    ImGuiContext& g = *GImGui;
11186
0
    ImGuiWindow* window = g.CurrentWindow;
11187
0
    IM_ASSERT(components > 0);
11188
0
    const ImGuiStyle& style = g.Style;
11189
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
11190
0
    float w_items = w_full - style.ItemInnerSpacing.x * (components - 1);
11191
0
    float prev_split = w_items;
11192
0
    for (int i = components - 1; i > 0; i--)
11193
0
    {
11194
0
        float next_split = IM_TRUNC(w_items * i / components);
11195
0
        window->DC.ItemWidthStack.push_back(ImMax(prev_split - next_split, 1.0f));
11196
0
        prev_split = next_split;
11197
0
    }
11198
0
    window->DC.ItemWidth = ImMax(prev_split, 1.0f);
11199
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
11200
0
}
11201
11202
void ImGui::PopItemWidth()
11203
0
{
11204
0
    ImGuiWindow* window = GetCurrentWindow();
11205
0
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
11206
0
    window->DC.ItemWidthStack.pop_back();
11207
0
}
11208
11209
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
11210
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
11211
float ImGui::CalcItemWidth()
11212
0
{
11213
0
    ImGuiContext& g = *GImGui;
11214
0
    ImGuiWindow* window = g.CurrentWindow;
11215
0
    float w;
11216
0
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
11217
0
        w = g.NextItemData.Width;
11218
0
    else
11219
0
        w = window->DC.ItemWidth;
11220
0
    if (w < 0.0f)
11221
0
    {
11222
0
        float region_max_x = GetContentRegionMaxAbs().x;
11223
0
        w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
11224
0
    }
11225
0
    w = IM_TRUNC(w);
11226
0
    return w;
11227
0
}
11228
11229
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
11230
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
11231
// Note that only CalcItemWidth() is publicly exposed.
11232
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
11233
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
11234
10.2k
{
11235
10.2k
    ImGuiContext& g = *GImGui;
11236
10.2k
    ImGuiWindow* window = g.CurrentWindow;
11237
11238
10.2k
    ImVec2 region_max;
11239
10.2k
    if (size.x < 0.0f || size.y < 0.0f)
11240
0
        region_max = GetContentRegionMaxAbs();
11241
11242
10.2k
    if (size.x == 0.0f)
11243
2.38k
        size.x = default_w;
11244
7.84k
    else if (size.x < 0.0f)
11245
0
        size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
11246
11247
10.2k
    if (size.y == 0.0f)
11248
1.61k
        size.y = default_h;
11249
8.62k
    else if (size.y < 0.0f)
11250
0
        size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
11251
11252
10.2k
    return size;
11253
10.2k
}
11254
11255
float ImGui::GetTextLineHeight()
11256
0
{
11257
0
    ImGuiContext& g = *GImGui;
11258
0
    return g.FontSize;
11259
0
}
11260
11261
float ImGui::GetTextLineHeightWithSpacing()
11262
10.2k
{
11263
10.2k
    ImGuiContext& g = *GImGui;
11264
10.2k
    return g.FontSize + g.Style.ItemSpacing.y;
11265
10.2k
}
11266
11267
float ImGui::GetFrameHeight()
11268
91
{
11269
91
    ImGuiContext& g = *GImGui;
11270
91
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
11271
91
}
11272
11273
float ImGui::GetFrameHeightWithSpacing()
11274
0
{
11275
0
    ImGuiContext& g = *GImGui;
11276
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
11277
0
}
11278
11279
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
11280
11281
// FIXME: This is in window space (not screen space!).
11282
ImVec2 ImGui::GetContentRegionMax()
11283
0
{
11284
0
    ImGuiContext& g = *GImGui;
11285
0
    ImGuiWindow* window = g.CurrentWindow;
11286
0
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
11287
0
    return mx - window->Pos;
11288
0
}
11289
11290
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
11291
ImVec2 ImGui::GetContentRegionMaxAbs()
11292
10.2k
{
11293
10.2k
    ImGuiContext& g = *GImGui;
11294
10.2k
    ImGuiWindow* window = g.CurrentWindow;
11295
10.2k
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
11296
10.2k
    return mx;
11297
10.2k
}
11298
11299
ImVec2 ImGui::GetContentRegionAvail()
11300
10.2k
{
11301
10.2k
    ImGuiWindow* window = GImGui->CurrentWindow;
11302
10.2k
    return GetContentRegionMaxAbs() - window->DC.CursorPos;
11303
10.2k
}
11304
11305
// In window space (not screen space!)
11306
ImVec2 ImGui::GetWindowContentRegionMin()
11307
0
{
11308
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11309
0
    return window->ContentRegionRect.Min - window->Pos;
11310
0
}
11311
11312
ImVec2 ImGui::GetWindowContentRegionMax()
11313
10.2k
{
11314
10.2k
    ImGuiWindow* window = GImGui->CurrentWindow;
11315
10.2k
    return window->ContentRegionRect.Max - window->Pos;
11316
10.2k
}
11317
11318
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
11319
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
11320
// FIXME-OPT: Could we safely early out on ->SkipItems?
11321
void ImGui::BeginGroup()
11322
0
{
11323
0
    ImGuiContext& g = *GImGui;
11324
0
    ImGuiWindow* window = g.CurrentWindow;
11325
11326
0
    g.GroupStack.resize(g.GroupStack.Size + 1);
11327
0
    ImGuiGroupData& group_data = g.GroupStack.back();
11328
0
    group_data.WindowID = window->ID;
11329
0
    group_data.BackupCursorPos = window->DC.CursorPos;
11330
0
    group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
11331
0
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
11332
0
    group_data.BackupIndent = window->DC.Indent;
11333
0
    group_data.BackupGroupOffset = window->DC.GroupOffset;
11334
0
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
11335
0
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
11336
0
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
11337
0
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
11338
0
    group_data.BackupIsSameLine = window->DC.IsSameLine;
11339
0
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
11340
0
    group_data.EmitItem = true;
11341
11342
0
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
11343
0
    window->DC.Indent = window->DC.GroupOffset;
11344
0
    window->DC.CursorMaxPos = window->DC.CursorPos;
11345
0
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
11346
0
    if (g.LogEnabled)
11347
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
11348
0
}
11349
11350
void ImGui::EndGroup()
11351
0
{
11352
0
    ImGuiContext& g = *GImGui;
11353
0
    ImGuiWindow* window = g.CurrentWindow;
11354
0
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
11355
11356
0
    ImGuiGroupData& group_data = g.GroupStack.back();
11357
0
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
11358
11359
0
    if (window->DC.IsSetPos)
11360
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
11361
11362
0
    ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
11363
11364
0
    window->DC.CursorPos = group_data.BackupCursorPos;
11365
0
    window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
11366
0
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
11367
0
    window->DC.Indent = group_data.BackupIndent;
11368
0
    window->DC.GroupOffset = group_data.BackupGroupOffset;
11369
0
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
11370
0
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
11371
0
    window->DC.IsSameLine = group_data.BackupIsSameLine;
11372
0
    if (g.LogEnabled)
11373
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
11374
11375
0
    if (!group_data.EmitItem)
11376
0
    {
11377
0
        g.GroupStack.pop_back();
11378
0
        return;
11379
0
    }
11380
11381
0
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset);      // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
11382
0
    ItemSize(group_bb.GetSize());
11383
0
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
11384
11385
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
11386
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
11387
    // Also if you grep for LastItemId you'll notice it is only used in that context.
11388
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
11389
0
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
11390
0
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
11391
0
    if (group_contains_curr_active_id)
11392
0
        g.LastItemData.ID = g.ActiveId;
11393
0
    else if (group_contains_prev_active_id)
11394
0
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
11395
0
    g.LastItemData.Rect = group_bb;
11396
11397
    // Forward Hovered flag
11398
0
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
11399
0
    if (group_contains_curr_hovered_id)
11400
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
11401
11402
    // Forward Edited flag
11403
0
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
11404
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
11405
11406
    // Forward Deactivated flag
11407
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
11408
0
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
11409
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
11410
11411
0
    g.GroupStack.pop_back();
11412
0
    if (g.DebugShowGroupRects)
11413
0
        window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
11414
0
}
11415
11416
11417
//-----------------------------------------------------------------------------
11418
// [SECTION] SCROLLING
11419
//-----------------------------------------------------------------------------
11420
11421
// Helper to snap on edges when aiming at an item very close to the edge,
11422
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
11423
// When we refactor the scrolling API this may be configurable with a flag?
11424
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
11425
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
11426
0
{
11427
0
    if (target <= snap_min + snap_threshold)
11428
0
        return ImLerp(snap_min, target, center_ratio);
11429
0
    if (target >= snap_max - snap_threshold)
11430
0
        return ImLerp(target, snap_max, center_ratio);
11431
0
    return target;
11432
0
}
11433
11434
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
11435
127k
{
11436
127k
    ImVec2 scroll = window->Scroll;
11437
127k
    ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
11438
381k
    for (int axis = 0; axis < 2; axis++)
11439
254k
    {
11440
254k
        if (window->ScrollTarget[axis] < FLT_MAX)
11441
5.37k
        {
11442
5.37k
            float center_ratio = window->ScrollTargetCenterRatio[axis];
11443
5.37k
            float scroll_target = window->ScrollTarget[axis];
11444
5.37k
            if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
11445
0
            {
11446
0
                float snap_min = 0.0f;
11447
0
                float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
11448
0
                scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
11449
0
            }
11450
5.37k
            scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
11451
5.37k
        }
11452
254k
        scroll[axis] = IM_ROUND(ImMax(scroll[axis], 0.0f));
11453
254k
        if (!window->Collapsed && !window->SkipItems)
11454
137k
            scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
11455
254k
    }
11456
127k
    return scroll;
11457
127k
}
11458
11459
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
11460
0
{
11461
0
    ImGuiContext& g = *GImGui;
11462
0
    ImGuiWindow* window = g.CurrentWindow;
11463
0
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
11464
0
}
11465
11466
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11467
0
{
11468
0
    ScrollToRectEx(window, item_rect, flags);
11469
0
}
11470
11471
// Scroll to keep newly navigated item fully into view
11472
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11473
5
{
11474
5
    ImGuiContext& g = *GImGui;
11475
5
    ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
11476
5
    scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
11477
5
    scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
11478
    //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
11479
    //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
11480
11481
    // Check that only one behavior is selected per axis
11482
5
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
11483
5
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
11484
11485
    // Defaults
11486
5
    ImGuiScrollFlags in_flags = flags;
11487
5
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
11488
0
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
11489
5
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
11490
5
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
11491
11492
5
    const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
11493
5
    const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
11494
5
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
11495
5
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
11496
11497
5
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
11498
0
    {
11499
0
        if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
11500
0
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
11501
0
        else if (item_rect.Max.x >= scroll_rect.Max.x)
11502
0
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
11503
0
    }
11504
5
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
11505
0
    {
11506
0
        if (can_be_fully_visible_x)
11507
0
            SetScrollFromPosX(window, ImTrunc((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
11508
0
        else
11509
0
            SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
11510
0
    }
11511
11512
5
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
11513
0
    {
11514
0
        if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
11515
0
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
11516
0
        else if (item_rect.Max.y >= scroll_rect.Max.y)
11517
0
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
11518
0
    }
11519
5
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
11520
0
    {
11521
0
        if (can_be_fully_visible_y)
11522
0
            SetScrollFromPosY(window, ImTrunc((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
11523
0
        else
11524
0
            SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
11525
0
    }
11526
11527
5
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
11528
5
    ImVec2 delta_scroll = next_scroll - window->Scroll;
11529
11530
    // Also scroll parent window to keep us into view if necessary
11531
5
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
11532
0
    {
11533
        // FIXME-SCROLL: May be an option?
11534
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
11535
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
11536
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
11537
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
11538
0
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
11539
0
    }
11540
11541
5
    return delta_scroll;
11542
5
}
11543
11544
float ImGui::GetScrollX()
11545
13.1k
{
11546
13.1k
    ImGuiWindow* window = GImGui->CurrentWindow;
11547
13.1k
    return window->Scroll.x;
11548
13.1k
}
11549
11550
float ImGui::GetScrollY()
11551
13.1k
{
11552
13.1k
    ImGuiWindow* window = GImGui->CurrentWindow;
11553
13.1k
    return window->Scroll.y;
11554
13.1k
}
11555
11556
float ImGui::GetScrollMaxX()
11557
0
{
11558
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11559
0
    return window->ScrollMax.x;
11560
0
}
11561
11562
float ImGui::GetScrollMaxY()
11563
0
{
11564
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11565
0
    return window->ScrollMax.y;
11566
0
}
11567
11568
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
11569
2.94k
{
11570
2.94k
    window->ScrollTarget.x = scroll_x;
11571
2.94k
    window->ScrollTargetCenterRatio.x = 0.0f;
11572
2.94k
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
11573
2.94k
}
11574
11575
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
11576
2.47k
{
11577
2.47k
    window->ScrollTarget.y = scroll_y;
11578
2.47k
    window->ScrollTargetCenterRatio.y = 0.0f;
11579
2.47k
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
11580
2.47k
}
11581
11582
void ImGui::SetScrollX(float scroll_x)
11583
2.93k
{
11584
2.93k
    ImGuiContext& g = *GImGui;
11585
2.93k
    SetScrollX(g.CurrentWindow, scroll_x);
11586
2.93k
}
11587
11588
void ImGui::SetScrollY(float scroll_y)
11589
2.44k
{
11590
2.44k
    ImGuiContext& g = *GImGui;
11591
2.44k
    SetScrollY(g.CurrentWindow, scroll_y);
11592
2.44k
}
11593
11594
// Note that a local position will vary depending on initial scroll value,
11595
// This is a little bit confusing so bear with us:
11596
//  - local_pos = (absolution_pos - window->Pos)
11597
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
11598
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
11599
//  - They mostly exist because of legacy API.
11600
// Following the rules above, when trying to work with scrolling code, consider that:
11601
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
11602
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
11603
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
11604
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
11605
0
{
11606
0
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
11607
0
    window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
11608
0
    window->ScrollTargetCenterRatio.x = center_x_ratio;
11609
0
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
11610
0
}
11611
11612
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
11613
0
{
11614
0
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
11615
0
    window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
11616
0
    window->ScrollTargetCenterRatio.y = center_y_ratio;
11617
0
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
11618
0
}
11619
11620
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
11621
0
{
11622
0
    ImGuiContext& g = *GImGui;
11623
0
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
11624
0
}
11625
11626
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
11627
0
{
11628
0
    ImGuiContext& g = *GImGui;
11629
0
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
11630
0
}
11631
11632
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
11633
void ImGui::SetScrollHereX(float center_x_ratio)
11634
0
{
11635
0
    ImGuiContext& g = *GImGui;
11636
0
    ImGuiWindow* window = g.CurrentWindow;
11637
0
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
11638
0
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
11639
0
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
11640
11641
    // Tweak: snap on edges when aiming at an item very close to the edge
11642
0
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
11643
0
}
11644
11645
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
11646
void ImGui::SetScrollHereY(float center_y_ratio)
11647
0
{
11648
0
    ImGuiContext& g = *GImGui;
11649
0
    ImGuiWindow* window = g.CurrentWindow;
11650
0
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
11651
0
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
11652
0
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
11653
11654
    // Tweak: snap on edges when aiming at an item very close to the edge
11655
0
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
11656
0
}
11657
11658
//-----------------------------------------------------------------------------
11659
// [SECTION] TOOLTIPS
11660
//-----------------------------------------------------------------------------
11661
11662
bool ImGui::BeginTooltip()
11663
0
{
11664
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11665
0
}
11666
11667
bool ImGui::BeginItemTooltip()
11668
0
{
11669
0
    if (!IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11670
0
        return false;
11671
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11672
0
}
11673
11674
bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
11675
0
{
11676
0
    ImGuiContext& g = *GImGui;
11677
11678
0
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
11679
0
    {
11680
        // Drag and Drop tooltips are positioning differently than other tooltips:
11681
        // - offset visibility to increase visibility around mouse.
11682
        // - never clamp within outer viewport boundary.
11683
        // We call SetNextWindowPos() to enforce position and disable clamping.
11684
        // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones).
11685
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
11686
0
        ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET * g.Style.MouseCursorScale;
11687
0
        SetNextWindowPos(tooltip_pos);
11688
0
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
11689
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
11690
0
        tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
11691
0
    }
11692
11693
0
    char window_name[16];
11694
0
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
11695
0
    if (tooltip_flags & ImGuiTooltipFlags_OverridePrevious)
11696
0
        if (ImGuiWindow* window = FindWindowByName(window_name))
11697
0
            if (window->Active)
11698
0
            {
11699
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
11700
0
                SetWindowHiddenAndSkipItemsForCurrentFrame(window);
11701
0
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
11702
0
            }
11703
0
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
11704
0
    Begin(window_name, NULL, flags | extra_window_flags);
11705
    // 2023-03-09: Added bool return value to the API, but currently always returning true.
11706
    // If this ever returns false we need to update BeginDragDropSource() accordingly.
11707
    //if (!ret)
11708
    //    End();
11709
    //return ret;
11710
0
    return true;
11711
0
}
11712
11713
void ImGui::EndTooltip()
11714
0
{
11715
0
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
11716
0
    End();
11717
0
}
11718
11719
void ImGui::SetTooltip(const char* fmt, ...)
11720
0
{
11721
0
    va_list args;
11722
0
    va_start(args, fmt);
11723
0
    SetTooltipV(fmt, args);
11724
0
    va_end(args);
11725
0
}
11726
11727
void ImGui::SetTooltipV(const char* fmt, va_list args)
11728
0
{
11729
0
    if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
11730
0
        return;
11731
0
    TextV(fmt, args);
11732
0
    EndTooltip();
11733
0
}
11734
11735
// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
11736
// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
11737
void ImGui::SetItemTooltip(const char* fmt, ...)
11738
0
{
11739
0
    va_list args;
11740
0
    va_start(args, fmt);
11741
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11742
0
        SetTooltipV(fmt, args);
11743
0
    va_end(args);
11744
0
}
11745
11746
void ImGui::SetItemTooltipV(const char* fmt, va_list args)
11747
0
{
11748
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11749
0
        SetTooltipV(fmt, args);
11750
0
}
11751
11752
11753
//-----------------------------------------------------------------------------
11754
// [SECTION] POPUPS
11755
//-----------------------------------------------------------------------------
11756
11757
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
11758
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
11759
0
{
11760
0
    ImGuiContext& g = *GImGui;
11761
0
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
11762
0
    {
11763
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
11764
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
11765
0
        IM_ASSERT(id == 0);
11766
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11767
0
            return g.OpenPopupStack.Size > 0;
11768
0
        else
11769
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
11770
0
    }
11771
0
    else
11772
0
    {
11773
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11774
0
        {
11775
            // Return true if the popup is open anywhere in the popup stack
11776
0
            for (ImGuiPopupData& popup_data : g.OpenPopupStack)
11777
0
                if (popup_data.PopupId == id)
11778
0
                    return true;
11779
0
            return false;
11780
0
        }
11781
0
        else
11782
0
        {
11783
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
11784
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
11785
0
        }
11786
0
    }
11787
0
}
11788
11789
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
11790
0
{
11791
0
    ImGuiContext& g = *GImGui;
11792
0
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
11793
0
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
11794
0
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
11795
0
    return IsPopupOpen(id, popup_flags);
11796
0
}
11797
11798
// Also see FindBlockingModal(NULL)
11799
ImGuiWindow* ImGui::GetTopMostPopupModal()
11800
175k
{
11801
175k
    ImGuiContext& g = *GImGui;
11802
175k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11803
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11804
0
            if (popup->Flags & ImGuiWindowFlags_Modal)
11805
0
                return popup;
11806
175k
    return NULL;
11807
175k
}
11808
11809
// See Demo->Stacked Modal to confirm what this is for.
11810
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
11811
58.4k
{
11812
58.4k
    ImGuiContext& g = *GImGui;
11813
58.4k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11814
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11815
0
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
11816
0
                return popup;
11817
58.4k
    return NULL;
11818
58.4k
}
11819
11820
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
11821
0
{
11822
0
    ImGuiContext& g = *GImGui;
11823
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11824
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
11825
0
    OpenPopupEx(id, popup_flags);
11826
0
}
11827
11828
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
11829
0
{
11830
0
    OpenPopupEx(id, popup_flags);
11831
0
}
11832
11833
// Mark popup as open (toggle toward open state).
11834
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
11835
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
11836
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
11837
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
11838
0
{
11839
0
    ImGuiContext& g = *GImGui;
11840
0
    ImGuiWindow* parent_window = g.CurrentWindow;
11841
0
    const int current_stack_size = g.BeginPopupStack.Size;
11842
11843
0
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
11844
0
        if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
11845
0
            return;
11846
11847
0
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
11848
0
    popup_ref.PopupId = id;
11849
0
    popup_ref.Window = NULL;
11850
0
    popup_ref.RestoreNavWindow = g.NavWindow;           // When popup closes focus may be restored to NavWindow (depend on window type).
11851
0
    popup_ref.OpenFrameCount = g.FrameCount;
11852
0
    popup_ref.OpenParentId = parent_window->IDStack.back();
11853
0
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
11854
0
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
11855
11856
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
11857
0
    if (g.OpenPopupStack.Size < current_stack_size + 1)
11858
0
    {
11859
0
        g.OpenPopupStack.push_back(popup_ref);
11860
0
    }
11861
0
    else
11862
0
    {
11863
        // Gently handle the user mistakenly calling OpenPopup() every frames: it is likely a programming mistake!
11864
        // However, if we were to run the regular code path, the ui would become completely unusable because the popup will always be
11865
        // in hidden-while-calculating-size state _while_ claiming focus. Which is extremely confusing situation for the programmer.
11866
        // Instead, for successive frames calls to OpenPopup(), we silently avoid reopening even if ImGuiPopupFlags_NoReopen is not specified.
11867
0
        bool keep_existing = false;
11868
0
        if (g.OpenPopupStack[current_stack_size].PopupId == id)
11869
0
            if ((g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) || (popup_flags & ImGuiPopupFlags_NoReopen))
11870
0
                keep_existing = true;
11871
0
        if (keep_existing)
11872
0
        {
11873
            // No reopen
11874
0
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
11875
0
        }
11876
0
        else
11877
0
        {
11878
            // Reopen: close child popups if any, then flag popup for open/reopen (set position, focus, init navigation)
11879
0
            ClosePopupToLevel(current_stack_size, true);
11880
0
            g.OpenPopupStack.push_back(popup_ref);
11881
0
        }
11882
11883
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
11884
        // This is equivalent to what ClosePopupToLevel() does.
11885
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
11886
        //    FocusWindow(parent_window);
11887
0
    }
11888
0
}
11889
11890
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
11891
// This function closes any popups that are over 'ref_window'.
11892
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
11893
4.92k
{
11894
4.92k
    ImGuiContext& g = *GImGui;
11895
4.92k
    if (g.OpenPopupStack.Size == 0)
11896
4.92k
        return;
11897
11898
    // Don't close our own child popup windows.
11899
    //IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window ? ref_window->Name : "<NULL>", restore_focus_to_window_under_popup);
11900
0
    int popup_count_to_keep = 0;
11901
0
    if (ref_window)
11902
0
    {
11903
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
11904
0
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
11905
0
        {
11906
0
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
11907
0
            if (!popup.Window)
11908
0
                continue;
11909
0
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
11910
11911
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
11912
            // - Clicking/Focusing Window2 won't close Popup1:
11913
            //     Window -> Popup1 -> Window2(Ref)
11914
            // - Clicking/focusing Popup1 will close Popup2 and Popup3:
11915
            //     Window -> Popup1(Ref) -> Popup2 -> Popup3
11916
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
11917
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
11918
            // We step through every popup from bottom to top to validate their position relative to reference window.
11919
0
            bool ref_window_is_descendent_of_popup = false;
11920
0
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
11921
0
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
11922
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
11923
0
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
11924
0
                    {
11925
0
                        ref_window_is_descendent_of_popup = true;
11926
0
                        break;
11927
0
                    }
11928
0
            if (!ref_window_is_descendent_of_popup)
11929
0
                break;
11930
0
        }
11931
0
    }
11932
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11933
0
    {
11934
0
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
11935
0
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
11936
0
    }
11937
0
}
11938
11939
void ImGui::ClosePopupsExceptModals()
11940
0
{
11941
0
    ImGuiContext& g = *GImGui;
11942
11943
0
    int popup_count_to_keep;
11944
0
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
11945
0
    {
11946
0
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
11947
0
        if (!window || (window->Flags & ImGuiWindowFlags_Modal))
11948
0
            break;
11949
0
    }
11950
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11951
0
        ClosePopupToLevel(popup_count_to_keep, true);
11952
0
}
11953
11954
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
11955
0
{
11956
0
    ImGuiContext& g = *GImGui;
11957
0
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup);
11958
0
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
11959
11960
    // Trim open popup stack
11961
0
    ImGuiPopupData prev_popup = g.OpenPopupStack[remaining];
11962
0
    g.OpenPopupStack.resize(remaining);
11963
11964
    // Restore focus (unless popup window was not yet submitted, and didn't have a chance to take focus anyhow. See #7325 for an edge case)
11965
0
    if (restore_focus_to_window_under_popup && prev_popup.Window)
11966
0
    {
11967
0
        ImGuiWindow* popup_window = prev_popup.Window;
11968
0
        ImGuiWindow* focus_window = (popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : prev_popup.RestoreNavWindow;
11969
0
        if (focus_window && !focus_window->WasActive)
11970
0
            FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
11971
0
        else
11972
0
            FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
11973
0
    }
11974
0
}
11975
11976
// Close the popup we have begin-ed into.
11977
void ImGui::CloseCurrentPopup()
11978
0
{
11979
0
    ImGuiContext& g = *GImGui;
11980
0
    int popup_idx = g.BeginPopupStack.Size - 1;
11981
0
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
11982
0
        return;
11983
11984
    // Closing a menu closes its top-most parent popup (unless a modal)
11985
0
    while (popup_idx > 0)
11986
0
    {
11987
0
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
11988
0
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
11989
0
        bool close_parent = false;
11990
0
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
11991
0
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
11992
0
                close_parent = true;
11993
0
        if (!close_parent)
11994
0
            break;
11995
0
        popup_idx--;
11996
0
    }
11997
0
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
11998
0
    ClosePopupToLevel(popup_idx, true);
11999
12000
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
12001
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
12002
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
12003
0
    if (ImGuiWindow* window = g.NavWindow)
12004
0
        window->DC.NavHideHighlightOneFrame = true;
12005
0
}
12006
12007
// Attention! BeginPopup() adds default flags when calling BeginPopupEx()!
12008
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags)
12009
0
{
12010
0
    ImGuiContext& g = *GImGui;
12011
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
12012
0
    {
12013
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12014
0
        return false;
12015
0
    }
12016
12017
0
    char name[20];
12018
0
    if (extra_window_flags & ImGuiWindowFlags_ChildMenu)
12019
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuDepth); // Recycle windows based on depth
12020
0
    else
12021
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
12022
12023
0
    bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking);
12024
0
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
12025
0
        EndPopup();
12026
12027
    //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
12028
12029
0
    return is_open;
12030
0
}
12031
12032
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
12033
0
{
12034
0
    ImGuiContext& g = *GImGui;
12035
0
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
12036
0
    {
12037
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12038
0
        return false;
12039
0
    }
12040
0
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
12041
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
12042
0
    return BeginPopupEx(id, flags);
12043
0
}
12044
12045
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
12046
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
12047
// - *p_open set back to false in BeginPopupModal() when popup is not open.
12048
// - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
12049
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
12050
0
{
12051
0
    ImGuiContext& g = *GImGui;
12052
0
    ImGuiWindow* window = g.CurrentWindow;
12053
0
    const ImGuiID id = window->GetID(name);
12054
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
12055
0
    {
12056
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12057
0
        if (p_open && *p_open)
12058
0
            *p_open = false;
12059
0
        return false;
12060
0
    }
12061
12062
    // Center modal windows by default for increased visibility
12063
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
12064
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
12065
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
12066
0
    {
12067
0
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
12068
0
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
12069
0
    }
12070
12071
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
12072
0
    const bool is_open = Begin(name, p_open, flags);
12073
0
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
12074
0
    {
12075
0
        EndPopup();
12076
0
        if (is_open)
12077
0
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
12078
0
        return false;
12079
0
    }
12080
0
    return is_open;
12081
0
}
12082
12083
void ImGui::EndPopup()
12084
0
{
12085
0
    ImGuiContext& g = *GImGui;
12086
0
    ImGuiWindow* window = g.CurrentWindow;
12087
0
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
12088
0
    IM_ASSERT(g.BeginPopupStack.Size > 0);
12089
12090
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
12091
0
    if (g.NavWindow == window)
12092
0
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
12093
12094
    // Child-popups don't need to be laid out
12095
0
    IM_ASSERT(g.WithinEndChild == false);
12096
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
12097
0
        g.WithinEndChild = true;
12098
0
    End();
12099
0
    g.WithinEndChild = false;
12100
0
}
12101
12102
// Helper to open a popup if mouse button is released over the item
12103
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
12104
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
12105
0
{
12106
0
    ImGuiContext& g = *GImGui;
12107
0
    ImGuiWindow* window = g.CurrentWindow;
12108
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12109
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12110
0
    {
12111
0
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
12112
0
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
12113
0
        OpenPopupEx(id, popup_flags);
12114
0
    }
12115
0
}
12116
12117
// This is a helper to handle the simplest case of associating one named popup to one given widget.
12118
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
12119
// - To create a popup with a specific identifier, pass it in str_id.
12120
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
12121
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
12122
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
12123
//   This is essentially the same as:
12124
//       id = str_id ? GetID(str_id) : GetItemID();
12125
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
12126
//       return BeginPopup(id);
12127
//   Which is essentially the same as:
12128
//       id = str_id ? GetID(str_id) : GetItemID();
12129
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
12130
//           OpenPopup(id);
12131
//       return BeginPopup(id);
12132
//   The main difference being that this is tweaked to avoid computing the ID twice.
12133
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
12134
0
{
12135
0
    ImGuiContext& g = *GImGui;
12136
0
    ImGuiWindow* window = g.CurrentWindow;
12137
0
    if (window->SkipItems)
12138
0
        return false;
12139
0
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
12140
0
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
12141
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12142
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12143
0
        OpenPopupEx(id, popup_flags);
12144
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
12145
0
}
12146
12147
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
12148
0
{
12149
0
    ImGuiContext& g = *GImGui;
12150
0
    ImGuiWindow* window = g.CurrentWindow;
12151
0
    if (!str_id)
12152
0
        str_id = "window_context";
12153
0
    ImGuiID id = window->GetID(str_id);
12154
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12155
0
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12156
0
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
12157
0
            OpenPopupEx(id, popup_flags);
12158
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
12159
0
}
12160
12161
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
12162
0
{
12163
0
    ImGuiContext& g = *GImGui;
12164
0
    ImGuiWindow* window = g.CurrentWindow;
12165
0
    if (!str_id)
12166
0
        str_id = "void_context";
12167
0
    ImGuiID id = window->GetID(str_id);
12168
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12169
0
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
12170
0
        if (GetTopMostPopupModal() == NULL)
12171
0
            OpenPopupEx(id, popup_flags);
12172
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
12173
0
}
12174
12175
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
12176
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
12177
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
12178
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
12179
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
12180
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
12181
0
{
12182
0
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
12183
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
12184
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
12185
12186
    // Combo Box policy (we want a connecting edge)
12187
0
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
12188
0
    {
12189
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
12190
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
12191
0
        {
12192
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
12193
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
12194
0
                continue;
12195
0
            ImVec2 pos;
12196
0
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
12197
0
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
12198
0
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
12199
0
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
12200
0
            if (!r_outer.Contains(ImRect(pos, pos + size)))
12201
0
                continue;
12202
0
            *last_dir = dir;
12203
0
            return pos;
12204
0
        }
12205
0
    }
12206
12207
    // Tooltip and Default popup policy
12208
    // (Always first try the direction we used on the last frame, if any)
12209
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
12210
0
    {
12211
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
12212
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
12213
0
        {
12214
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
12215
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
12216
0
                continue;
12217
12218
0
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
12219
0
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
12220
12221
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
12222
0
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
12223
0
                continue;
12224
0
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
12225
0
                continue;
12226
12227
0
            ImVec2 pos;
12228
0
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
12229
0
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
12230
12231
            // Clamp top-left corner of popup
12232
0
            pos.x = ImMax(pos.x, r_outer.Min.x);
12233
0
            pos.y = ImMax(pos.y, r_outer.Min.y);
12234
12235
0
            *last_dir = dir;
12236
0
            return pos;
12237
0
        }
12238
0
    }
12239
12240
    // Fallback when not enough room:
12241
0
    *last_dir = ImGuiDir_None;
12242
12243
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
12244
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
12245
0
        return ref_pos + ImVec2(2, 2);
12246
12247
    // Otherwise try to keep within display
12248
0
    ImVec2 pos = ref_pos;
12249
0
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
12250
0
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
12251
0
    return pos;
12252
0
}
12253
12254
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
12255
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
12256
0
{
12257
0
    ImGuiContext& g = *GImGui;
12258
0
    ImRect r_screen;
12259
0
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
12260
0
    {
12261
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
12262
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
12263
0
        r_screen.Min = monitor.WorkPos;
12264
0
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
12265
0
    }
12266
0
    else
12267
0
    {
12268
        // Use the full viewport area (not work area) for popups
12269
0
        r_screen = window->Viewport->GetMainRect();
12270
0
    }
12271
0
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
12272
0
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
12273
0
    return r_screen;
12274
0
}
12275
12276
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
12277
0
{
12278
0
    ImGuiContext& g = *GImGui;
12279
12280
0
    ImRect r_outer = GetPopupAllowedExtentRect(window);
12281
0
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
12282
0
    {
12283
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
12284
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
12285
0
        ImGuiWindow* parent_window = window->ParentWindow;
12286
0
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
12287
0
        ImRect r_avoid;
12288
0
        if (parent_window->DC.MenuBarAppending)
12289
0
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
12290
0
        else
12291
0
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
12292
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
12293
0
    }
12294
0
    if (window->Flags & ImGuiWindowFlags_Popup)
12295
0
    {
12296
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
12297
0
    }
12298
0
    if (window->Flags & ImGuiWindowFlags_Tooltip)
12299
0
    {
12300
        // Position tooltip (always follows mouse + clamp within outer boundaries)
12301
        // Note that drag and drop tooltips are NOT using this path: BeginTooltipEx() manually sets their position.
12302
        // In theory we could handle both cases in same location, but requires a bit of shuffling as drag and drop tooltips are calling SetWindowPos() leading to 'window_pos_set_by_api' being set in Begin()
12303
0
        IM_ASSERT(g.CurrentWindow == window);
12304
0
        const float scale = g.Style.MouseCursorScale;
12305
0
        const ImVec2 ref_pos = NavCalcPreferredRefPos();
12306
0
        const ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET * scale;
12307
0
        ImRect r_avoid;
12308
0
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
12309
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
12310
0
        else
12311
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
12312
        //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
12313
0
        return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
12314
0
    }
12315
0
    IM_ASSERT(0);
12316
0
    return window->Pos;
12317
0
}
12318
12319
//-----------------------------------------------------------------------------
12320
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
12321
//-----------------------------------------------------------------------------
12322
12323
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
12324
// In our terminology those should be interchangeable, yet right now this is super confusing.
12325
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
12326
12327
void ImGui::SetNavWindow(ImGuiWindow* window)
12328
4.56k
{
12329
4.56k
    ImGuiContext& g = *GImGui;
12330
4.56k
    if (g.NavWindow != window)
12331
4.56k
    {
12332
4.56k
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
12333
4.56k
        g.NavWindow = window;
12334
4.56k
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12335
4.56k
    }
12336
4.56k
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12337
4.56k
    NavUpdateAnyRequestFlag();
12338
4.56k
}
12339
12340
void ImGui::NavHighlightActivated(ImGuiID id)
12341
13
{
12342
13
    ImGuiContext& g = *GImGui;
12343
13
    g.NavHighlightActivatedId = id;
12344
13
    g.NavHighlightActivatedTimer = NAV_ACTIVATE_HIGHLIGHT_TIMER;
12345
13
}
12346
12347
void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
12348
527
{
12349
527
    ImGuiContext& g = *GImGui;
12350
527
    g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
12351
527
}
12352
12353
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
12354
237
{
12355
237
    ImGuiContext& g = *GImGui;
12356
237
    IM_ASSERT(g.NavWindow != NULL);
12357
237
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
12358
237
    g.NavId = id;
12359
237
    g.NavLayer = nav_layer;
12360
237
    SetNavFocusScope(focus_scope_id);
12361
237
    g.NavWindow->NavLastIds[nav_layer] = id;
12362
237
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
12363
12364
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12365
237
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12366
237
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12367
237
}
12368
12369
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
12370
1
{
12371
1
    ImGuiContext& g = *GImGui;
12372
1
    IM_ASSERT(id != 0);
12373
12374
1
    if (g.NavWindow != window)
12375
1
       SetNavWindow(window);
12376
12377
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
12378
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
12379
1
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
12380
1
    g.NavId = id;
12381
1
    g.NavLayer = nav_layer;
12382
1
    SetNavFocusScope(g.CurrentFocusScopeId);
12383
1
    window->NavLastIds[nav_layer] = id;
12384
1
    if (g.LastItemData.ID == id)
12385
1
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
12386
12387
1
    if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
12388
1
        g.NavDisableMouseHover = true;
12389
0
    else
12390
0
        g.NavDisableHighlight = true;
12391
12392
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12393
1
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12394
1
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12395
1
}
12396
12397
static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
12398
7
{
12399
7
    if (ImFabs(dx) > ImFabs(dy))
12400
0
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
12401
7
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
12402
7
}
12403
12404
static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
12405
14
{
12406
14
    if (cand_max < curr_min)
12407
4
        return cand_max - curr_min;
12408
10
    if (curr_max < cand_min)
12409
3
        return cand_min - curr_max;
12410
7
    return 0.0f;
12411
10
}
12412
12413
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
12414
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
12415
29
{
12416
29
    ImGuiContext& g = *GImGui;
12417
29
    ImGuiWindow* window = g.CurrentWindow;
12418
29
    if (g.NavLayer != window->DC.NavLayerCurrent)
12419
22
        return false;
12420
12421
    // FIXME: Those are not good variables names
12422
7
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
12423
7
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
12424
7
    g.NavScoringDebugCount++;
12425
12426
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
12427
7
    if (window->ParentWindow == g.NavWindow)
12428
0
    {
12429
0
        IM_ASSERT((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened);
12430
0
        if (!window->ClipRect.Overlaps(cand))
12431
0
            return false;
12432
0
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
12433
0
    }
12434
12435
    // Compute distance between boxes
12436
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
12437
7
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
12438
7
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
12439
7
    if (dby != 0.0f && dbx != 0.0f)
12440
0
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
12441
7
    float dist_box = ImFabs(dbx) + ImFabs(dby);
12442
12443
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
12444
7
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
12445
7
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
12446
7
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
12447
12448
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
12449
7
    ImGuiDir quadrant;
12450
7
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
12451
7
    if (dbx != 0.0f || dby != 0.0f)
12452
7
    {
12453
        // For non-overlapping boxes, use distance between boxes
12454
        // FIXME-NAV: Quadrant may be incorrect because of (1) dbx bias and (2) curr.Max.y bias applied by NavBiasScoringRect() where typically curr.Max.y==curr.Min.y
12455
        // One typical case where this happens, with style.WindowMenuButtonPosition == ImGuiDir_Right, pressing Left to navigate from Close to Collapse tends to fail.
12456
        // Also see #6344. Calling ImGetDirQuadrantFromDelta() with unbiased values may be good but side-effects are plenty.
12457
7
        dax = dbx;
12458
7
        day = dby;
12459
7
        dist_axial = dist_box;
12460
7
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
12461
7
    }
12462
0
    else if (dcx != 0.0f || dcy != 0.0f)
12463
0
    {
12464
        // For overlapping boxes with different centers, use distance between centers
12465
0
        dax = dcx;
12466
0
        day = dcy;
12467
0
        dist_axial = dist_center;
12468
0
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
12469
0
    }
12470
0
    else
12471
0
    {
12472
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
12473
0
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
12474
0
    }
12475
12476
7
    const ImGuiDir move_dir = g.NavMoveDir;
12477
#if IMGUI_DEBUG_NAV_SCORING
12478
    char buf[200];
12479
    if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
12480
    {
12481
        if (quadrant == move_dir)
12482
        {
12483
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
12484
            ImDrawList* draw_list = GetForegroundDrawList(window);
12485
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
12486
            draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
12487
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
12488
        }
12489
    }
12490
    const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
12491
    const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
12492
    if (debug_hovering || debug_tty)
12493
    {
12494
        ImFormatString(buf, IM_ARRAYSIZE(buf),
12495
            "d-box    (%7.3f,%7.3f) -> %7.3f\nd-center (%7.3f,%7.3f) -> %7.3f\nd-axial  (%7.3f,%7.3f) -> %7.3f\nnav %c, quadrant %c",
12496
            dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
12497
        if (debug_hovering)
12498
        {
12499
            ImDrawList* draw_list = GetForegroundDrawList(window);
12500
            draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
12501
            draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
12502
            draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
12503
            draw_list->AddText(cand.Max, ~0U, buf);
12504
        }
12505
        if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
12506
    }
12507
#endif
12508
12509
    // Is it in the quadrant we're interested in moving to?
12510
7
    bool new_best = false;
12511
7
    if (quadrant == move_dir)
12512
7
    {
12513
        // Does it beat the current best candidate?
12514
7
        if (dist_box < result->DistBox)
12515
7
        {
12516
7
            result->DistBox = dist_box;
12517
7
            result->DistCenter = dist_center;
12518
7
            return true;
12519
7
        }
12520
0
        if (dist_box == result->DistBox)
12521
0
        {
12522
            // Try using distance between center points to break ties
12523
0
            if (dist_center < result->DistCenter)
12524
0
            {
12525
0
                result->DistCenter = dist_center;
12526
0
                new_best = true;
12527
0
            }
12528
0
            else if (dist_center == result->DistCenter)
12529
0
            {
12530
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
12531
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
12532
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
12533
0
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
12534
0
                    new_best = true;
12535
0
            }
12536
0
        }
12537
0
    }
12538
12539
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
12540
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
12541
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
12542
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
12543
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
12544
0
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
12545
0
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
12546
0
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
12547
0
            {
12548
0
                result->DistAxial = dist_axial;
12549
0
                new_best = true;
12550
0
            }
12551
12552
0
    return new_best;
12553
7
}
12554
12555
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
12556
69
{
12557
69
    ImGuiContext& g = *GImGui;
12558
69
    ImGuiWindow* window = g.CurrentWindow;
12559
69
    result->Window = window;
12560
69
    result->ID = g.LastItemData.ID;
12561
69
    result->FocusScopeId = g.CurrentFocusScopeId;
12562
69
    result->InFlags = g.LastItemData.InFlags;
12563
69
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
12564
69
    if (result->InFlags & ImGuiItemFlags_HasSelectionUserData)
12565
0
    {
12566
0
        IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12567
0
        result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12568
0
    }
12569
69
}
12570
12571
// True when current work location may be scrolled horizontally when moving left / right.
12572
// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
12573
void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
12574
195k
{
12575
195k
    ImGuiContext& g = *GImGui;
12576
195k
    ImGuiWindow* window = g.CurrentWindow;
12577
195k
    window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
12578
195k
}
12579
12580
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
12581
// This is called after LastItemData is set, but NextItemData is also still valid.
12582
static void ImGui::NavProcessItem()
12583
375
{
12584
375
    ImGuiContext& g = *GImGui;
12585
375
    ImGuiWindow* window = g.CurrentWindow;
12586
375
    const ImGuiID id = g.LastItemData.ID;
12587
375
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
12588
12589
    // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
12590
375
    if (window->DC.NavIsScrollPushableX == false)
12591
0
    {
12592
0
        g.LastItemData.NavRect.Min.x = ImClamp(g.LastItemData.NavRect.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
12593
0
        g.LastItemData.NavRect.Max.x = ImClamp(g.LastItemData.NavRect.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
12594
0
    }
12595
375
    const ImRect nav_bb = g.LastItemData.NavRect;
12596
12597
    // Process Init Request
12598
375
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
12599
62
    {
12600
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
12601
62
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
12602
62
        if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
12603
62
        {
12604
62
            NavApplyItemToResult(&g.NavInitResult);
12605
62
        }
12606
62
        if (candidate_for_nav_default_focus)
12607
0
        {
12608
0
            g.NavInitRequest = false; // Found a match, clear request
12609
0
            NavUpdateAnyRequestFlag();
12610
0
        }
12611
62
    }
12612
12613
    // Process Move Request (scoring for navigation)
12614
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
12615
375
    if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
12616
37
    {
12617
37
        if ((g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) || (window->Flags & ImGuiWindowFlags_NoNavInputs) == 0)
12618
37
        {
12619
37
            const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
12620
37
            if (is_tabbing)
12621
8
            {
12622
8
                NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
12623
8
            }
12624
29
            else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
12625
24
            {
12626
24
                ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
12627
24
                if (NavScoreItem(result))
12628
7
                    NavApplyItemToResult(result);
12629
12630
                // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
12631
24
                const float VISIBLE_RATIO = 0.70f;
12632
24
                if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
12633
5
                    if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
12634
5
                        if (NavScoreItem(&g.NavMoveResultLocalVisible))
12635
0
                            NavApplyItemToResult(&g.NavMoveResultLocalVisible);
12636
24
            }
12637
37
        }
12638
37
    }
12639
12640
    // Update information for currently focused/navigated item
12641
375
    if (g.NavId == id)
12642
241
    {
12643
241
        if (g.NavWindow != window)
12644
0
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
12645
241
        g.NavLayer = window->DC.NavLayerCurrent;
12646
241
        SetNavFocusScope(g.CurrentFocusScopeId); // Will set g.NavFocusScopeId AND store g.NavFocusScopePath
12647
241
        g.NavFocusScopeId = g.CurrentFocusScopeId;
12648
241
        g.NavIdIsAlive = true;
12649
241
        if (g.LastItemData.InFlags & ImGuiItemFlags_HasSelectionUserData)
12650
0
        {
12651
0
            IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12652
0
            g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12653
0
        }
12654
241
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
12655
241
    }
12656
375
}
12657
12658
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
12659
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
12660
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
12661
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
12662
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
12663
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
12664
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
12665
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
12666
8
{
12667
8
    ImGuiContext& g = *GImGui;
12668
12669
8
    if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
12670
8
    {
12671
8
        if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
12672
5
            return;
12673
3
        if (g.NavFocusScopeId != g.CurrentFocusScopeId)
12674
3
            return;
12675
3
    }
12676
12677
    // - Can always land on an item when using API call.
12678
    // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
12679
    // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
12680
0
    bool can_stop;
12681
0
    if (move_flags & ImGuiNavMoveFlags_FocusApi)
12682
0
        can_stop = true;
12683
0
    else
12684
0
        can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
12685
12686
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
12687
0
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
12688
0
    if (g.NavTabbingDir == +1)
12689
0
    {
12690
        // Tab Forward or SetKeyboardFocusHere() with >= 0
12691
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0)
12692
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12693
0
        if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
12694
0
            NavMoveRequestResolveWithLastItem(result);
12695
0
        else if (g.NavId == id)
12696
0
            g.NavTabbingCounter = 1;
12697
0
    }
12698
0
    else if (g.NavTabbingDir == -1)
12699
0
    {
12700
        // Tab Backward
12701
0
        if (g.NavId == id)
12702
0
        {
12703
0
            if (result->ID)
12704
0
            {
12705
0
                g.NavMoveScoringItems = false;
12706
0
                NavUpdateAnyRequestFlag();
12707
0
            }
12708
0
        }
12709
0
        else if (can_stop)
12710
0
        {
12711
            // Keep applying until reaching NavId
12712
0
            NavApplyItemToResult(result);
12713
0
        }
12714
0
    }
12715
0
    else if (g.NavTabbingDir == 0)
12716
0
    {
12717
0
        if (can_stop && g.NavId == id)
12718
0
            NavMoveRequestResolveWithLastItem(result);
12719
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
12720
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12721
0
    }
12722
0
}
12723
12724
bool ImGui::NavMoveRequestButNoResultYet()
12725
5.72k
{
12726
5.72k
    ImGuiContext& g = *GImGui;
12727
5.72k
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
12728
5.72k
}
12729
12730
// FIXME: ScoringRect is not set
12731
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12732
104
{
12733
104
    ImGuiContext& g = *GImGui;
12734
104
    IM_ASSERT(g.NavWindow != NULL);
12735
12736
104
    if (move_flags & ImGuiNavMoveFlags_IsTabbing)
12737
39
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
12738
12739
104
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
12740
104
    g.NavMoveDir = move_dir;
12741
104
    g.NavMoveDirForDebug = move_dir;
12742
104
    g.NavMoveClipDir = clip_dir;
12743
104
    g.NavMoveFlags = move_flags;
12744
104
    g.NavMoveScrollFlags = scroll_flags;
12745
104
    g.NavMoveForwardToNextFrame = false;
12746
104
    g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods;
12747
104
    g.NavMoveResultLocal.Clear();
12748
104
    g.NavMoveResultLocalVisible.Clear();
12749
104
    g.NavMoveResultOther.Clear();
12750
104
    g.NavTabbingCounter = 0;
12751
104
    g.NavTabbingResultFirst.Clear();
12752
104
    NavUpdateAnyRequestFlag();
12753
104
}
12754
12755
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
12756
0
{
12757
0
    ImGuiContext& g = *GImGui;
12758
0
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
12759
0
    NavApplyItemToResult(result);
12760
0
    NavUpdateAnyRequestFlag();
12761
0
}
12762
12763
// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere
12764
void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiTreeNodeStackData* tree_node_data)
12765
0
{
12766
0
    ImGuiContext& g = *GImGui;
12767
0
    g.NavMoveScoringItems = false;
12768
0
    g.LastItemData.ID = tree_node_data->ID;
12769
0
    g.LastItemData.InFlags = tree_node_data->InFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
12770
0
    g.LastItemData.NavRect = tree_node_data->NavRect;
12771
0
    NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
12772
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12773
0
    NavUpdateAnyRequestFlag();
12774
0
}
12775
12776
void ImGui::NavMoveRequestCancel()
12777
92
{
12778
92
    ImGuiContext& g = *GImGui;
12779
92
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12780
92
    NavUpdateAnyRequestFlag();
12781
92
}
12782
12783
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
12784
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12785
0
{
12786
0
    ImGuiContext& g = *GImGui;
12787
0
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
12788
0
    NavMoveRequestCancel();
12789
0
    g.NavMoveForwardToNextFrame = true;
12790
0
    g.NavMoveDir = move_dir;
12791
0
    g.NavMoveClipDir = clip_dir;
12792
0
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
12793
0
    g.NavMoveScrollFlags = scroll_flags;
12794
0
}
12795
12796
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
12797
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
12798
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
12799
0
{
12800
0
    ImGuiContext& g = *GImGui;
12801
0
    IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
12802
12803
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
12804
    // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
12805
0
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
12806
0
        g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
12807
0
}
12808
12809
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
12810
// This way we could find the last focused window among our children. It would be much less confusing this way?
12811
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
12812
3.54k
{
12813
3.54k
    ImGuiWindow* parent = nav_window;
12814
6.84k
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12815
3.29k
        parent = parent->ParentWindow;
12816
3.54k
    if (parent && parent != nav_window)
12817
3.29k
        parent->NavLastChildNavWindow = nav_window;
12818
3.54k
}
12819
12820
// Restore the last focused child.
12821
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
12822
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
12823
25
{
12824
25
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
12825
25
        return window->NavLastChildNavWindow;
12826
0
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
12827
0
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
12828
0
            return tab->Window;
12829
0
    return window;
12830
0
}
12831
12832
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
12833
87
{
12834
87
    ImGuiContext& g = *GImGui;
12835
87
    if (layer == ImGuiNavLayer_Main)
12836
25
    {
12837
25
        ImGuiWindow* prev_nav_window = g.NavWindow;
12838
25
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
12839
25
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12840
25
        if (prev_nav_window)
12841
25
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
12842
25
    }
12843
87
    ImGuiWindow* window = g.NavWindow;
12844
87
    if (window->NavLastIds[layer] != 0)
12845
5
    {
12846
5
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
12847
5
    }
12848
82
    else
12849
82
    {
12850
82
        g.NavLayer = layer;
12851
82
        NavInitWindow(window, true);
12852
82
    }
12853
87
}
12854
12855
void ImGui::NavRestoreHighlightAfterMove()
12856
180
{
12857
180
    ImGuiContext& g = *GImGui;
12858
180
    g.NavDisableHighlight = false;
12859
180
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
12860
180
}
12861
12862
static inline void ImGui::NavUpdateAnyRequestFlag()
12863
63.3k
{
12864
63.3k
    ImGuiContext& g = *GImGui;
12865
63.3k
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
12866
63.3k
    if (g.NavAnyRequest)
12867
63.3k
        IM_ASSERT(g.NavWindow != NULL);
12868
63.3k
}
12869
12870
// This needs to be called before we submit any widget (aka in or before Begin)
12871
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
12872
96
{
12873
    // FIXME: ChildWindow test here is wrong for docking
12874
96
    ImGuiContext& g = *GImGui;
12875
96
    IM_ASSERT(window == g.NavWindow);
12876
12877
96
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
12878
0
    {
12879
0
        g.NavId = 0;
12880
0
        SetNavFocusScope(window->NavRootFocusScopeId);
12881
0
        return;
12882
0
    }
12883
12884
96
    bool init_for_nav = false;
12885
96
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
12886
96
        init_for_nav = true;
12887
96
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
12888
96
    if (init_for_nav)
12889
96
    {
12890
96
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
12891
96
        g.NavInitRequest = true;
12892
96
        g.NavInitRequestFromMove = false;
12893
96
        g.NavInitResult.ID = 0;
12894
96
        NavUpdateAnyRequestFlag();
12895
96
    }
12896
0
    else
12897
0
    {
12898
0
        g.NavId = window->NavLastIds[0];
12899
0
        SetNavFocusScope(window->NavRootFocusScopeId);
12900
0
    }
12901
96
}
12902
12903
static ImVec2 ImGui::NavCalcPreferredRefPos()
12904
0
{
12905
0
    ImGuiContext& g = *GImGui;
12906
0
    ImGuiWindow* window = g.NavWindow;
12907
0
    const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
12908
12909
    // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag.
12910
0
    if ((g.NavDisableHighlight || !g.NavDisableMouseHover || !window) && !activated_shortcut)
12911
0
    {
12912
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
12913
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
12914
        // In theory we could move that +1.0f offset in OpenPopupEx()
12915
0
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
12916
0
        return ImVec2(p.x + 1.0f, p.y);
12917
0
    }
12918
0
    else
12919
0
    {
12920
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
12921
0
        ImRect ref_rect;
12922
0
        if (activated_shortcut)
12923
0
            ref_rect = g.LastItemData.NavRect;
12924
0
        else
12925
0
            ref_rect = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
12926
12927
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
12928
0
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
12929
0
        {
12930
0
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12931
0
            ref_rect.Translate(window->Scroll - next_scroll);
12932
0
        }
12933
0
        ImVec2 pos = ImVec2(ref_rect.Min.x + ImMin(g.Style.FramePadding.x * 4, ref_rect.GetWidth()), ref_rect.Max.y - ImMin(g.Style.FramePadding.y, ref_rect.GetHeight()));
12934
0
        ImGuiViewport* viewport = window->Viewport;
12935
0
        return ImTrunc(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
12936
0
    }
12937
0
}
12938
12939
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
12940
0
{
12941
0
    ImGuiContext& g = *GImGui;
12942
0
    float repeat_delay, repeat_rate;
12943
0
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
12944
12945
0
    ImGuiKey key_less, key_more;
12946
0
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
12947
0
    {
12948
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
12949
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
12950
0
    }
12951
0
    else
12952
0
    {
12953
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
12954
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
12955
0
    }
12956
0
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
12957
0
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
12958
0
        amount = 0.0f;
12959
0
    return amount;
12960
0
}
12961
12962
static void ImGui::NavUpdate()
12963
58.4k
{
12964
58.4k
    ImGuiContext& g = *GImGui;
12965
58.4k
    ImGuiIO& io = g.IO;
12966
12967
58.4k
    io.WantSetMousePos = false;
12968
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
12969
12970
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
12971
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
12972
58.4k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12973
58.4k
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
12974
58.4k
    if (nav_gamepad_active)
12975
0
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
12976
0
            if (IsKeyDown(key))
12977
0
                g.NavInputSource = ImGuiInputSource_Gamepad;
12978
58.4k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12979
58.4k
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
12980
58.4k
    if (nav_keyboard_active)
12981
58.4k
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
12982
409k
            if (IsKeyDown(key))
12983
28.2k
                g.NavInputSource = ImGuiInputSource_Keyboard;
12984
12985
    // Process navigation init request (select first/default focus)
12986
58.4k
    g.NavJustMovedToId = 0;
12987
58.4k
    g.NavJustMovedToFocusScopeId = g.NavJustMovedFromFocusScopeId = 0;
12988
58.4k
    if (g.NavInitResult.ID != 0)
12989
62
        NavInitRequestApplyResult();
12990
58.4k
    g.NavInitRequest = false;
12991
58.4k
    g.NavInitRequestFromMove = false;
12992
58.4k
    g.NavInitResult.ID = 0;
12993
12994
    // Process navigation move request
12995
58.4k
    if (g.NavMoveSubmitted)
12996
56
        NavMoveRequestApplyResult();
12997
58.4k
    g.NavTabbingCounter = 0;
12998
58.4k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12999
13000
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
13001
58.4k
    bool set_mouse_pos = false;
13002
58.4k
    if (g.NavMousePosDirty && g.NavIdIsAlive)
13003
79
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
13004
75
            set_mouse_pos = true;
13005
58.4k
    g.NavMousePosDirty = false;
13006
58.4k
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
13007
13008
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
13009
58.4k
    if (g.NavWindow)
13010
3.54k
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
13011
58.4k
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
13012
62
        g.NavWindow->NavLastChildNavWindow = NULL;
13013
13014
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
13015
58.4k
    NavUpdateWindowing();
13016
13017
    // Set output flags for user application
13018
58.4k
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
13019
58.4k
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
13020
13021
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
13022
58.4k
    NavUpdateCancelRequest();
13023
13024
    // Process manual activation request
13025
58.4k
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
13026
58.4k
    g.NavActivateFlags = ImGuiActivateFlags_None;
13027
58.4k
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
13028
353
    {
13029
353
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_NoOwner));
13030
353
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, 0, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, 0, ImGuiKeyOwner_NoOwner)));
13031
353
        const bool input_down = (nav_keyboard_active && (IsKeyDown(ImGuiKey_Enter, ImGuiKeyOwner_NoOwner) || IsKeyDown(ImGuiKey_KeypadEnter, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_NoOwner));
13032
353
        const bool input_pressed = input_down && ((nav_keyboard_active && (IsKeyPressed(ImGuiKey_Enter, 0, ImGuiKeyOwner_NoOwner) || IsKeyPressed(ImGuiKey_KeypadEnter, 0, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, 0, ImGuiKeyOwner_NoOwner)));
13033
353
        if (g.ActiveId == 0 && activate_pressed)
13034
13
        {
13035
13
            g.NavActivateId = g.NavId;
13036
13
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
13037
13
        }
13038
353
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
13039
0
        {
13040
0
            g.NavActivateId = g.NavId;
13041
0
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
13042
0
        }
13043
353
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
13044
13
            g.NavActivateDownId = g.NavId;
13045
353
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
13046
13
        {
13047
13
            g.NavActivatePressedId = g.NavId;
13048
13
            NavHighlightActivated(g.NavId);
13049
13
        }
13050
353
    }
13051
58.4k
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
13052
0
        g.NavDisableHighlight = true;
13053
58.4k
    if (g.NavActivateId != 0)
13054
58.4k
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
13055
13056
    // Highlight
13057
58.4k
    if (g.NavHighlightActivatedTimer > 0.0f)
13058
73
        g.NavHighlightActivatedTimer = ImMax(0.0f, g.NavHighlightActivatedTimer - io.DeltaTime);
13059
58.4k
    if (g.NavHighlightActivatedTimer == 0.0f)
13060
58.4k
        g.NavHighlightActivatedId = 0;
13061
13062
    // Process programmatic activation request
13063
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
13064
58.4k
    if (g.NavNextActivateId != 0)
13065
0
    {
13066
0
        g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
13067
0
        g.NavActivateFlags = g.NavNextActivateFlags;
13068
0
    }
13069
58.4k
    g.NavNextActivateId = 0;
13070
13071
    // Process move requests
13072
58.4k
    NavUpdateCreateMoveRequest();
13073
58.4k
    if (g.NavMoveDir == ImGuiDir_None)
13074
58.4k
        NavUpdateCreateTabbingRequest();
13075
58.4k
    NavUpdateAnyRequestFlag();
13076
58.4k
    g.NavIdIsAlive = false;
13077
13078
    // Scrolling
13079
58.4k
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
13080
3.54k
    {
13081
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
13082
3.54k
        ImGuiWindow* window = g.NavWindow;
13083
3.54k
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
13084
3.54k
        const ImGuiDir move_dir = g.NavMoveDir;
13085
3.54k
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
13086
33
        {
13087
33
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
13088
5
                SetScrollX(window, ImTrunc(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
13089
33
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
13090
28
                SetScrollY(window, ImTrunc(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
13091
33
        }
13092
13093
        // *Normal* Manual scroll with LStick
13094
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
13095
3.54k
        if (nav_gamepad_active)
13096
0
        {
13097
0
            const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
13098
0
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
13099
0
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
13100
0
                SetScrollX(window, ImTrunc(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
13101
0
            if (scroll_dir.y != 0.0f)
13102
0
                SetScrollY(window, ImTrunc(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
13103
0
        }
13104
3.54k
    }
13105
13106
    // Always prioritize mouse highlight if navigation is disabled
13107
58.4k
    if (!nav_keyboard_active && !nav_gamepad_active)
13108
0
    {
13109
0
        g.NavDisableHighlight = true;
13110
0
        g.NavDisableMouseHover = set_mouse_pos = false;
13111
0
    }
13112
13113
    // Update mouse position if requested
13114
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
13115
58.4k
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
13116
0
        TeleportMousePos(NavCalcPreferredRefPos());
13117
13118
    // [DEBUG]
13119
58.4k
    g.NavScoringDebugCount = 0;
13120
#if IMGUI_DEBUG_NAV_RECTS
13121
    if (ImGuiWindow* debug_window = g.NavWindow)
13122
    {
13123
        ImDrawList* draw_list = GetForegroundDrawList(debug_window);
13124
        int layer = g.NavLayer; /* for (int layer = 0; layer < 2; layer++)*/ { ImRect r = WindowRectRelToAbs(debug_window, debug_window->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 200, 0, 255)); }
13125
        //if (1) { ImU32 col = (!debug_window->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
13126
    }
13127
#endif
13128
58.4k
}
13129
13130
void ImGui::NavInitRequestApplyResult()
13131
62
{
13132
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
13133
62
    ImGuiContext& g = *GImGui;
13134
62
    if (!g.NavWindow)
13135
18
        return;
13136
13137
44
    ImGuiNavItemData* result = &g.NavInitResult;
13138
44
    if (g.NavId != result->ID)
13139
35
    {
13140
35
        g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
13141
35
        g.NavJustMovedToId = result->ID;
13142
35
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
13143
35
        g.NavJustMovedToKeyMods = 0;
13144
35
        g.NavJustMovedToIsTabbing = false;
13145
35
        g.NavJustMovedToHasSelectionData = (result->InFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
13146
35
    }
13147
13148
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
13149
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
13150
44
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
13151
44
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
13152
44
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
13153
44
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
13154
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
13155
44
    if (g.NavInitRequestFromMove)
13156
0
        NavRestoreHighlightAfterMove();
13157
44
}
13158
13159
// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
13160
static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
13161
65
{
13162
    // Bias initial rect
13163
65
    ImGuiContext& g = *GImGui;
13164
65
    const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
13165
13166
    // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
13167
    // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
13168
    // - But each successful move sets new bias on one axis, only cleared when using mouse.
13169
65
    if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
13170
65
    {
13171
65
        if (preferred_pos_rel.x == FLT_MAX)
13172
29
            preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
13173
65
        if (preferred_pos_rel.y == FLT_MAX)
13174
43
            preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
13175
65
    }
13176
13177
    // Apply general bias on the other axis
13178
65
    if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
13179
53
        r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
13180
12
    else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
13181
12
        r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
13182
65
}
13183
13184
void ImGui::NavUpdateCreateMoveRequest()
13185
58.4k
{
13186
58.4k
    ImGuiContext& g = *GImGui;
13187
58.4k
    ImGuiIO& io = g.IO;
13188
58.4k
    ImGuiWindow* window = g.NavWindow;
13189
58.4k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13190
58.4k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13191
13192
58.4k
    if (g.NavMoveForwardToNextFrame && window != NULL)
13193
0
    {
13194
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
13195
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
13196
0
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
13197
0
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
13198
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
13199
0
    }
13200
58.4k
    else
13201
58.4k
    {
13202
        // Initiate directional inputs request
13203
58.4k
        g.NavMoveDir = ImGuiDir_None;
13204
58.4k
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
13205
58.4k
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
13206
58.4k
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
13207
3.54k
        {
13208
3.54k
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
13209
3.54k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Left; }
13210
3.54k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Right; }
13211
3.54k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Up; }
13212
3.54k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Down; }
13213
3.54k
        }
13214
58.4k
        g.NavMoveClipDir = g.NavMoveDir;
13215
58.4k
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
13216
58.4k
    }
13217
13218
    // Update PageUp/PageDown/Home/End scroll
13219
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
13220
58.4k
    float scoring_rect_offset_y = 0.0f;
13221
58.4k
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
13222
3.49k
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
13223
58.4k
    if (scoring_rect_offset_y != 0.0f)
13224
13
    {
13225
13
        g.NavScoringNoClipRect = window->InnerRect;
13226
13
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
13227
13
    }
13228
13229
    // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
13230
#if IMGUI_DEBUG_NAV_SCORING
13231
    //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
13232
    //    g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
13233
    if (io.KeyCtrl)
13234
    {
13235
        if (g.NavMoveDir == ImGuiDir_None)
13236
            g.NavMoveDir = g.NavMoveDirForDebug;
13237
        g.NavMoveClipDir = g.NavMoveDir;
13238
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
13239
    }
13240
#endif
13241
13242
    // Submit
13243
58.4k
    g.NavMoveForwardToNextFrame = false;
13244
58.4k
    if (g.NavMoveDir != ImGuiDir_None)
13245
65
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
13246
13247
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
13248
58.4k
    if (g.NavMoveSubmitted && g.NavId == 0)
13249
48
    {
13250
48
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
13251
48
        g.NavInitRequest = g.NavInitRequestFromMove = true;
13252
48
        g.NavInitResult.ID = 0;
13253
48
        g.NavDisableHighlight = false;
13254
48
    }
13255
13256
    // When using gamepad, we project the reference nav bounding box into window visible area.
13257
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
13258
    // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
13259
58.4k
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
13260
0
    {
13261
0
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
13262
0
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
13263
0
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
13264
13265
        // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
13266
        // Otherwise 'inner_rect_rel' would be off on the move result frame.
13267
0
        inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
13268
13269
0
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
13270
0
        {
13271
0
            IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
13272
0
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
13273
0
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
13274
0
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
13275
0
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
13276
0
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
13277
0
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
13278
0
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
13279
0
            g.NavId = 0;
13280
0
        }
13281
0
    }
13282
13283
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
13284
58.4k
    ImRect scoring_rect;
13285
58.4k
    if (window != NULL)
13286
3.54k
    {
13287
3.54k
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
13288
3.54k
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
13289
3.54k
        scoring_rect.TranslateY(scoring_rect_offset_y);
13290
3.54k
        if (g.NavMoveSubmitted)
13291
65
            NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags);
13292
3.54k
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
13293
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
13294
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
13295
3.54k
    }
13296
58.4k
    g.NavScoringRect = scoring_rect;
13297
58.4k
    g.NavScoringNoClipRect.Add(scoring_rect);
13298
58.4k
}
13299
13300
void ImGui::NavUpdateCreateTabbingRequest()
13301
58.4k
{
13302
58.4k
    ImGuiContext& g = *GImGui;
13303
58.4k
    ImGuiWindow* window = g.NavWindow;
13304
58.4k
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
13305
58.4k
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
13306
54.9k
        return;
13307
13308
3.47k
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
13309
3.47k
    if (!tab_pressed)
13310
3.44k
        return;
13311
13312
    // Initiate tabbing request
13313
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
13314
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
13315
39
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13316
39
    if (nav_keyboard_active)
13317
39
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
13318
0
    else
13319
0
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
13320
39
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
13321
39
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
13322
39
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
13323
39
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
13324
39
    g.NavTabbingCounter = -1;
13325
39
}
13326
13327
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
13328
void ImGui::NavMoveRequestApplyResult()
13329
56
{
13330
56
    ImGuiContext& g = *GImGui;
13331
#if IMGUI_DEBUG_NAV_SCORING
13332
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
13333
        return;
13334
#endif
13335
13336
    // Select which result to use
13337
56
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
13338
13339
    // Tabbing forward wrap
13340
56
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
13341
25
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
13342
0
            result = &g.NavTabbingResultFirst;
13343
13344
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
13345
56
    const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
13346
56
    if (result == NULL)
13347
51
    {
13348
51
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
13349
25
            g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
13350
51
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
13351
1
            NavRestoreHighlightAfterMove();
13352
51
        NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
13353
51
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
13354
51
        return;
13355
51
    }
13356
13357
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
13358
5
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
13359
3
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
13360
0
            result = &g.NavMoveResultLocalVisible;
13361
13362
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
13363
5
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
13364
0
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
13365
0
            result = &g.NavMoveResultOther;
13366
5
    IM_ASSERT(g.NavWindow && result->Window);
13367
13368
    // Scroll to keep newly navigated item fully into view.
13369
5
    if (g.NavLayer == ImGuiNavLayer_Main)
13370
5
    {
13371
5
        ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
13372
5
        ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
13373
13374
5
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
13375
2
        {
13376
            // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
13377
2
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
13378
2
            SetScrollY(result->Window, scroll_target);
13379
2
        }
13380
5
    }
13381
13382
5
    if (g.NavWindow != result->Window)
13383
0
    {
13384
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
13385
0
        g.NavWindow = result->Window;
13386
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13387
0
    }
13388
13389
    // Clear active id unless requested not to
13390
    // FIXME: ImGuiNavMoveFlags_NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction,
13391
    // so this is mostly provided as a gateway for further experiments (see #1418, #2890)
13392
5
    if (g.ActiveId != result->ID && (g.NavMoveFlags & ImGuiNavMoveFlags_NoClearActiveId) == 0)
13393
5
        ClearActiveID();
13394
13395
    // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
13396
    // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
13397
5
    if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
13398
3
    {
13399
3
        g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
13400
3
        g.NavJustMovedToId = result->ID;
13401
3
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
13402
3
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
13403
3
        g.NavJustMovedToIsTabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
13404
3
        g.NavJustMovedToHasSelectionData = (result->InFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
13405
        //IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId);
13406
3
    }
13407
13408
    // Apply new NavID/Focus
13409
5
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
13410
5
    ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
13411
5
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
13412
5
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
13413
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
13414
13415
    // Restore last preferred position for current axis
13416
    // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
13417
5
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
13418
5
    {
13419
5
        preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
13420
5
        g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
13421
5
    }
13422
13423
    // Tabbing: Activates Inputable, otherwise only Focus
13424
5
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->InFlags & ImGuiItemFlags_Inputable) == 0)
13425
0
        g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
13426
13427
    // Activate
13428
5
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
13429
0
    {
13430
0
        g.NavNextActivateId = result->ID;
13431
0
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
13432
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
13433
0
            g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
13434
0
    }
13435
13436
    // Enable nav highlight
13437
5
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
13438
5
        NavRestoreHighlightAfterMove();
13439
5
}
13440
13441
// Process NavCancel input (to close a popup, get back to parent, clear focus)
13442
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
13443
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
13444
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
13445
static void ImGui::NavUpdateCancelRequest()
13446
58.4k
{
13447
58.4k
    ImGuiContext& g = *GImGui;
13448
58.4k
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13449
58.4k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13450
58.4k
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, 0, ImGuiKeyOwner_NoOwner)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, 0, ImGuiKeyOwner_NoOwner)))
13451
57.6k
        return;
13452
13453
785
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
13454
785
    if (g.ActiveId != 0)
13455
0
    {
13456
0
        ClearActiveID();
13457
0
    }
13458
785
    else if (g.NavLayer != ImGuiNavLayer_Main)
13459
0
    {
13460
        // Leave the "menu" layer
13461
0
        NavRestoreLayer(ImGuiNavLayer_Main);
13462
0
        NavRestoreHighlightAfterMove();
13463
0
    }
13464
785
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow)
13465
87
    {
13466
        // Exit child window
13467
87
        ImGuiWindow* child_window = g.NavWindow->RootWindowForNav;
13468
87
        ImGuiWindow* parent_window = child_window->ParentWindow;
13469
87
        IM_ASSERT(child_window->ChildId != 0);
13470
87
        FocusWindow(parent_window);
13471
87
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_window->Rect()));
13472
87
        NavRestoreHighlightAfterMove();
13473
87
    }
13474
698
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
13475
0
    {
13476
        // Close open popup/menu
13477
0
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
13478
0
    }
13479
698
    else
13480
698
    {
13481
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
13482
698
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
13483
3
            g.NavWindow->NavLastIds[0] = 0;
13484
698
        g.NavId = 0;
13485
698
    }
13486
785
}
13487
13488
// Handle PageUp/PageDown/Home/End keys
13489
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
13490
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
13491
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
13492
static float ImGui::NavUpdatePageUpPageDown()
13493
3.49k
{
13494
3.49k
    ImGuiContext& g = *GImGui;
13495
3.49k
    ImGuiWindow* window = g.NavWindow;
13496
3.49k
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
13497
0
        return 0.0f;
13498
13499
3.49k
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_NoOwner);
13500
3.49k
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_NoOwner);
13501
3.49k
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
13502
3.49k
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
13503
3.49k
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
13504
3.18k
        return 0.0f;
13505
13506
310
    if (g.NavLayer != ImGuiNavLayer_Main)
13507
0
        NavRestoreLayer(ImGuiNavLayer_Main);
13508
13509
310
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
13510
207
    {
13511
        // Fallback manual-scroll when window has no navigable item
13512
207
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
13513
0
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
13514
207
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
13515
1
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
13516
206
        else if (home_pressed)
13517
1
            SetScrollY(window, 0.0f);
13518
205
        else if (end_pressed)
13519
0
            SetScrollY(window, window->ScrollMax.y);
13520
207
    }
13521
103
    else
13522
103
    {
13523
103
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
13524
103
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
13525
103
        float nav_scoring_rect_offset_y = 0.0f;
13526
103
        if (IsKeyPressed(ImGuiKey_PageUp, true))
13527
8
        {
13528
8
            nav_scoring_rect_offset_y = -page_offset_y;
13529
8
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
13530
8
            g.NavMoveClipDir = ImGuiDir_Up;
13531
8
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13532
8
        }
13533
95
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
13534
5
        {
13535
5
            nav_scoring_rect_offset_y = +page_offset_y;
13536
5
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
13537
5
            g.NavMoveClipDir = ImGuiDir_Down;
13538
5
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13539
5
        }
13540
90
        else if (home_pressed)
13541
3
        {
13542
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
13543
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
13544
            // Preserve current horizontal position if we have any.
13545
3
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
13546
3
            if (nav_rect_rel.IsInverted())
13547
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13548
3
            g.NavMoveDir = ImGuiDir_Down;
13549
3
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13550
            // FIXME-NAV: MoveClipDir left to _None, intentional?
13551
3
        }
13552
87
        else if (end_pressed)
13553
0
        {
13554
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
13555
0
            if (nav_rect_rel.IsInverted())
13556
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13557
0
            g.NavMoveDir = ImGuiDir_Up;
13558
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13559
            // FIXME-NAV: MoveClipDir left to _None, intentional?
13560
0
        }
13561
103
        return nav_scoring_rect_offset_y;
13562
103
    }
13563
207
    return 0.0f;
13564
310
}
13565
13566
static void ImGui::NavEndFrame()
13567
58.4k
{
13568
58.4k
    ImGuiContext& g = *GImGui;
13569
13570
    // Show CTRL+TAB list window
13571
58.4k
    if (g.NavWindowingTarget != NULL)
13572
0
        NavUpdateWindowingOverlay();
13573
13574
    // Perform wrap-around in menus
13575
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
13576
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
13577
58.4k
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
13578
0
        NavUpdateCreateWrappingRequest();
13579
58.4k
}
13580
13581
static void ImGui::NavUpdateCreateWrappingRequest()
13582
0
{
13583
0
    ImGuiContext& g = *GImGui;
13584
0
    ImGuiWindow* window = g.NavWindow;
13585
13586
0
    bool do_forward = false;
13587
0
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
13588
0
    ImGuiDir clip_dir = g.NavMoveDir;
13589
13590
0
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
13591
    //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
13592
0
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13593
0
    {
13594
0
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
13595
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
13596
0
        {
13597
0
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
13598
0
            clip_dir = ImGuiDir_Up;
13599
0
        }
13600
0
        do_forward = true;
13601
0
    }
13602
0
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13603
0
    {
13604
0
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
13605
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
13606
0
        {
13607
0
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
13608
0
            clip_dir = ImGuiDir_Down;
13609
0
        }
13610
0
        do_forward = true;
13611
0
    }
13612
0
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13613
0
    {
13614
0
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
13615
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
13616
0
        {
13617
0
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
13618
0
            clip_dir = ImGuiDir_Left;
13619
0
        }
13620
0
        do_forward = true;
13621
0
    }
13622
0
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13623
0
    {
13624
0
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
13625
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
13626
0
        {
13627
0
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
13628
0
            clip_dir = ImGuiDir_Right;
13629
0
        }
13630
0
        do_forward = true;
13631
0
    }
13632
0
    if (!do_forward)
13633
0
        return;
13634
0
    window->NavRectRel[g.NavLayer] = bb_rel;
13635
0
    NavClearPreferredPosForAxis(ImGuiAxis_X);
13636
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
13637
0
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
13638
0
}
13639
13640
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
13641
0
{
13642
0
    ImGuiContext& g = *GImGui;
13643
0
    IM_UNUSED(g);
13644
0
    int order = window->FocusOrder;
13645
0
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
13646
0
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
13647
0
    return order;
13648
0
}
13649
13650
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
13651
0
{
13652
0
    ImGuiContext& g = *GImGui;
13653
0
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
13654
0
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
13655
0
            return g.WindowsFocusOrder[i];
13656
0
    return NULL;
13657
0
}
13658
13659
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
13660
0
{
13661
0
    ImGuiContext& g = *GImGui;
13662
0
    IM_ASSERT(g.NavWindowingTarget);
13663
0
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
13664
0
        return;
13665
13666
0
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
13667
0
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
13668
0
    if (!window_target)
13669
0
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
13670
0
    if (window_target) // Don't reset windowing target if there's a single window in the list
13671
0
    {
13672
0
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
13673
0
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13674
0
    }
13675
0
    g.NavWindowingToggleLayer = false;
13676
0
}
13677
13678
// Windowing management mode
13679
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
13680
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
13681
static void ImGui::NavUpdateWindowing()
13682
58.4k
{
13683
58.4k
    ImGuiContext& g = *GImGui;
13684
58.4k
    ImGuiIO& io = g.IO;
13685
13686
58.4k
    ImGuiWindow* apply_focus_window = NULL;
13687
58.4k
    bool apply_toggle_layer = false;
13688
13689
58.4k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
13690
58.4k
    bool allow_windowing = (modal_window == NULL); // FIXME: This prevent CTRL+TAB from being usable with windows that are inside the Begin-stack of that modal.
13691
58.4k
    if (!allow_windowing)
13692
0
        g.NavWindowingTarget = NULL;
13693
13694
    // Fade out
13695
58.4k
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
13696
0
    {
13697
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
13698
0
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
13699
0
            g.NavWindowingTargetAnim = NULL;
13700
0
    }
13701
13702
    // Start CTRL+Tab or Square+L/R window selection
13703
    // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab)
13704
58.4k
    const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing");
13705
58.4k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13706
58.4k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13707
58.4k
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
13708
58.4k
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
13709
58.4k
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_None);
13710
58.4k
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
13711
58.4k
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
13712
0
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
13713
0
        {
13714
0
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
13715
0
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
13716
0
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13717
0
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
13718
0
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
13719
13720
            // Manually register ownership of our mods. Using a global route in the Shortcut() calls instead would probably be correct but may have more side-effects.
13721
0
            if (keyboard_next_window || keyboard_prev_window)
13722
0
                SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
13723
0
        }
13724
13725
    // Gamepad update
13726
58.4k
    g.NavWindowingTimer += io.DeltaTime;
13727
58.4k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
13728
0
    {
13729
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
13730
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
13731
13732
        // Select window to focus
13733
0
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
13734
0
        if (focus_change_dir != 0)
13735
0
        {
13736
0
            NavUpdateWindowingHighlightWindow(focus_change_dir);
13737
0
            g.NavWindowingHighlightAlpha = 1.0f;
13738
0
        }
13739
13740
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
13741
0
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
13742
0
        {
13743
0
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
13744
0
            if (g.NavWindowingToggleLayer && g.NavWindow)
13745
0
                apply_toggle_layer = true;
13746
0
            else if (!g.NavWindowingToggleLayer)
13747
0
                apply_focus_window = g.NavWindowingTarget;
13748
0
            g.NavWindowingTarget = NULL;
13749
0
        }
13750
0
    }
13751
13752
    // Keyboard: Focus
13753
58.4k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
13754
0
    {
13755
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
13756
0
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
13757
0
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
13758
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
13759
0
        if (keyboard_next_window || keyboard_prev_window)
13760
0
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
13761
0
        else if ((io.KeyMods & shared_mods) != shared_mods)
13762
0
            apply_focus_window = g.NavWindowingTarget;
13763
0
    }
13764
13765
    // Keyboard: Press and Release ALT to toggle menu layer
13766
58.4k
    const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt };
13767
58.4k
    for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
13768
116k
        if (nav_keyboard_active && IsKeyPressed(windowing_toggle_key, 0, ImGuiKeyOwner_NoOwner))
13769
676
        {
13770
676
            g.NavWindowingToggleLayer = true;
13771
676
            g.NavWindowingToggleKey = windowing_toggle_key;
13772
676
            g.NavInputSource = ImGuiInputSource_Keyboard;
13773
676
            break;
13774
676
        }
13775
58.4k
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
13776
3.13k
    {
13777
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
13778
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
13779
        // - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl).
13780
        // We cancel toggling nav layer if an owner has claimed the key.
13781
3.13k
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)
13782
54
            g.NavWindowingToggleLayer = false;
13783
3.13k
        if (TestKeyOwner(g.NavWindowingToggleKey, ImGuiKeyOwner_NoOwner) == false || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_NoOwner) == false)
13784
0
            g.NavWindowingToggleLayer = false;
13785
13786
        // Apply layer toggle on Alt release
13787
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
13788
3.13k
        if (IsKeyReleased(g.NavWindowingToggleKey) && g.NavWindowingToggleLayer)
13789
450
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
13790
450
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
13791
450
                    apply_toggle_layer = true;
13792
3.13k
        if (!IsKeyDown(g.NavWindowingToggleKey))
13793
635
            g.NavWindowingToggleLayer = false;
13794
3.13k
    }
13795
13796
    // Move window
13797
58.4k
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
13798
0
    {
13799
0
        ImVec2 nav_move_dir;
13800
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
13801
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
13802
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
13803
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
13804
0
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
13805
0
        {
13806
0
            const float NAV_MOVE_SPEED = 800.0f;
13807
0
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
13808
0
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
13809
0
            g.NavDisableMouseHover = true;
13810
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos);
13811
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
13812
0
            {
13813
0
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
13814
0
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
13815
0
                g.NavWindowingAccumDeltaPos -= accum_floored;
13816
0
            }
13817
0
        }
13818
0
    }
13819
13820
    // Apply final focus
13821
58.4k
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
13822
0
    {
13823
        // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow()
13824
        // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
13825
0
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
13826
0
        ClearActiveID();
13827
0
        NavRestoreHighlightAfterMove();
13828
0
        ClosePopupsOverWindow(apply_focus_window, false);
13829
0
        FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
13830
0
        apply_focus_window = g.NavWindow;
13831
0
        if (apply_focus_window->NavLastIds[0] == 0)
13832
0
            NavInitWindow(apply_focus_window, false);
13833
13834
        // If the window has ONLY a menu layer (no main layer), select it directly
13835
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
13836
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
13837
        // the target window as already been previewed once.
13838
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
13839
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
13840
        // won't be valid.
13841
0
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
13842
0
            g.NavLayer = ImGuiNavLayer_Menu;
13843
13844
        // Request OS level focus
13845
0
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
13846
0
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
13847
0
    }
13848
58.4k
    if (apply_focus_window)
13849
0
        g.NavWindowingTarget = NULL;
13850
13851
    // Apply menu/layer toggle
13852
58.4k
    if (apply_toggle_layer && g.NavWindow)
13853
87
    {
13854
87
        ClearActiveID();
13855
13856
        // Move to parent menu if necessary
13857
87
        ImGuiWindow* new_nav_window = g.NavWindow;
13858
149
        while (new_nav_window->ParentWindow
13859
149
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
13860
149
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
13861
149
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
13862
62
            new_nav_window = new_nav_window->ParentWindow;
13863
87
        if (new_nav_window != g.NavWindow)
13864
62
        {
13865
62
            ImGuiWindow* old_nav_window = g.NavWindow;
13866
62
            FocusWindow(new_nav_window);
13867
62
            new_nav_window->NavLastChildNavWindow = old_nav_window;
13868
62
        }
13869
13870
        // Toggle layer
13871
87
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
13872
87
        if (new_nav_layer != g.NavLayer)
13873
87
        {
13874
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
13875
87
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
13876
87
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
13877
62
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
13878
87
            NavRestoreLayer(new_nav_layer);
13879
87
            NavRestoreHighlightAfterMove();
13880
87
        }
13881
87
    }
13882
58.4k
}
13883
13884
// Window has already passed the IsWindowNavFocusable()
13885
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
13886
0
{
13887
0
    if (window->Flags & ImGuiWindowFlags_Popup)
13888
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
13889
0
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
13890
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
13891
0
    if (window->DockNodeAsHost)
13892
0
        return "(Dock node)"; // Not normally shown to user.
13893
0
    return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
13894
0
}
13895
13896
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
13897
void ImGui::NavUpdateWindowingOverlay()
13898
0
{
13899
0
    ImGuiContext& g = *GImGui;
13900
0
    IM_ASSERT(g.NavWindowingTarget != NULL);
13901
13902
0
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
13903
0
        return;
13904
13905
0
    if (g.NavWindowingListWindow == NULL)
13906
0
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
13907
0
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
13908
0
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
13909
0
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
13910
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
13911
0
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
13912
0
    if (g.ContextName[0] != 0)
13913
0
        SeparatorText(g.ContextName);
13914
0
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
13915
0
    {
13916
0
        ImGuiWindow* window = g.WindowsFocusOrder[n];
13917
0
        IM_ASSERT(window != NULL); // Fix static analyzers
13918
0
        if (!IsWindowNavFocusable(window))
13919
0
            continue;
13920
0
        const char* label = window->Name;
13921
0
        if (label == FindRenderedTextEnd(label))
13922
0
            label = GetFallbackWindowNameForWindowingList(window);
13923
0
        Selectable(label, g.NavWindowingTarget == window);
13924
0
    }
13925
0
    End();
13926
0
    PopStyleVar();
13927
0
}
13928
13929
13930
//-----------------------------------------------------------------------------
13931
// [SECTION] DRAG AND DROP
13932
//-----------------------------------------------------------------------------
13933
13934
bool ImGui::IsDragDropActive()
13935
0
{
13936
0
    ImGuiContext& g = *GImGui;
13937
0
    return g.DragDropActive;
13938
0
}
13939
13940
void ImGui::ClearDragDrop()
13941
2
{
13942
2
    ImGuiContext& g = *GImGui;
13943
2
    if (g.DragDropActive)
13944
1
        IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] ClearDragDrop()\n");
13945
2
    g.DragDropActive = false;
13946
2
    g.DragDropPayload.Clear();
13947
2
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
13948
2
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
13949
2
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
13950
2
    g.DragDropAcceptFrameCount = -1;
13951
13952
2
    g.DragDropPayloadBufHeap.clear();
13953
2
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13954
2
}
13955
13956
bool ImGui::BeginTooltipHidden()
13957
0
{
13958
0
    ImGuiContext& g = *GImGui;
13959
0
    bool ret = Begin("##Tooltip_Hidden", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
13960
0
    SetWindowHiddenAndSkipItemsForCurrentFrame(g.CurrentWindow);
13961
0
    return ret;
13962
0
}
13963
13964
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
13965
// If the item has an identifier:
13966
// - This assume/require the item to be activated (typically via ButtonBehavior).
13967
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
13968
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
13969
// If the item has no identifier:
13970
// - Currently always assume left mouse button.
13971
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
13972
90
{
13973
90
    ImGuiContext& g = *GImGui;
13974
90
    ImGuiWindow* window = g.CurrentWindow;
13975
13976
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
13977
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
13978
90
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
13979
13980
90
    bool source_drag_active = false;
13981
90
    ImGuiID source_id = 0;
13982
90
    ImGuiID source_parent_id = 0;
13983
90
    if ((flags & ImGuiDragDropFlags_SourceExtern) == 0)
13984
90
    {
13985
90
        source_id = g.LastItemData.ID;
13986
90
        if (source_id != 0)
13987
90
        {
13988
            // Common path: items with ID
13989
90
            if (g.ActiveId != source_id)
13990
0
                return false;
13991
90
            if (g.ActiveIdMouseButton != -1)
13992
0
                mouse_button = g.ActiveIdMouseButton;
13993
90
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13994
0
                return false;
13995
90
            g.ActiveIdAllowOverlap = false;
13996
90
        }
13997
0
        else
13998
0
        {
13999
            // Uncommon path: items without ID
14000
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
14001
0
                return false;
14002
0
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
14003
0
                return false;
14004
14005
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
14006
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
14007
0
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
14008
0
            {
14009
0
                IM_ASSERT(0);
14010
0
                return false;
14011
0
            }
14012
14013
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
14014
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
14015
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
14016
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
14017
            // Rely on keeping other window->LastItemXXX fields intact.
14018
0
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
14019
0
            KeepAliveID(source_id);
14020
0
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.InFlags);
14021
0
            if (is_hovered && g.IO.MouseClicked[mouse_button])
14022
0
            {
14023
0
                SetActiveID(source_id, window);
14024
0
                FocusWindow(window);
14025
0
            }
14026
0
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
14027
0
                g.ActiveIdAllowOverlap = is_hovered;
14028
0
        }
14029
90
        if (g.ActiveId != source_id)
14030
0
            return false;
14031
90
        source_parent_id = window->IDStack.back();
14032
90
        source_drag_active = IsMouseDragging(mouse_button);
14033
14034
        // Disable navigation and key inputs while dragging + cancel existing request if any
14035
90
        SetActiveIdUsingAllKeyboardKeys();
14036
90
    }
14037
0
    else
14038
0
    {
14039
        // When ImGuiDragDropFlags_SourceExtern is set:
14040
0
        window = NULL;
14041
0
        source_id = ImHashStr("#SourceExtern");
14042
0
        source_drag_active = true;
14043
0
        mouse_button = g.IO.MouseDown[0] ? 0 : -1;
14044
0
        KeepAliveID(source_id);
14045
0
        SetActiveID(source_id, NULL);
14046
0
    }
14047
14048
90
    IM_ASSERT(g.DragDropWithinTarget == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
14049
90
    if (!source_drag_active)
14050
0
        return false;
14051
14052
    // Activate drag and drop
14053
90
    if (!g.DragDropActive)
14054
1
    {
14055
1
        IM_ASSERT(source_id != 0);
14056
1
        ClearDragDrop();
14057
1
        IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] BeginDragDropSource() DragDropActive = true, source_id = 0x%08X%s\n",
14058
1
            source_id, (flags & ImGuiDragDropFlags_SourceExtern) ? " (EXTERN)" : "");
14059
1
        ImGuiPayload& payload = g.DragDropPayload;
14060
1
        payload.SourceId = source_id;
14061
1
        payload.SourceParentId = source_parent_id;
14062
1
        g.DragDropActive = true;
14063
1
        g.DragDropSourceFlags = flags;
14064
1
        g.DragDropMouseButton = mouse_button;
14065
1
        if (payload.SourceId == g.ActiveId)
14066
1
            g.ActiveIdNoClearOnFocusLoss = true;
14067
1
    }
14068
90
    g.DragDropSourceFrameCount = g.FrameCount;
14069
90
    g.DragDropWithinSource = true;
14070
14071
90
    if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
14072
0
    {
14073
        // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
14074
        // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
14075
0
        bool ret;
14076
0
        if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
14077
0
            ret = BeginTooltipHidden();
14078
0
        else
14079
0
            ret = BeginTooltip();
14080
0
        IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
14081
0
        IM_UNUSED(ret);
14082
0
    }
14083
14084
90
    if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
14085
90
        g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
14086
14087
90
    return true;
14088
90
}
14089
14090
void ImGui::EndDragDropSource()
14091
90
{
14092
90
    ImGuiContext& g = *GImGui;
14093
90
    IM_ASSERT(g.DragDropActive);
14094
90
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
14095
14096
90
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
14097
0
        EndTooltip();
14098
14099
    // Discard the drag if have not called SetDragDropPayload()
14100
90
    if (g.DragDropPayload.DataFrameCount == -1)
14101
0
        ClearDragDrop();
14102
90
    g.DragDropWithinSource = false;
14103
90
}
14104
14105
// Use 'cond' to choose to submit payload on drag start or every frame
14106
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
14107
90
{
14108
90
    ImGuiContext& g = *GImGui;
14109
90
    ImGuiPayload& payload = g.DragDropPayload;
14110
90
    if (cond == 0)
14111
90
        cond = ImGuiCond_Always;
14112
14113
90
    IM_ASSERT(type != NULL);
14114
90
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
14115
90
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
14116
90
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
14117
90
    IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
14118
14119
90
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
14120
90
    {
14121
        // Copy payload
14122
90
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
14123
90
        g.DragDropPayloadBufHeap.resize(0);
14124
90
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
14125
0
        {
14126
            // Store in heap
14127
0
            g.DragDropPayloadBufHeap.resize((int)data_size);
14128
0
            payload.Data = g.DragDropPayloadBufHeap.Data;
14129
0
            memcpy(payload.Data, data, data_size);
14130
0
        }
14131
90
        else if (data_size > 0)
14132
90
        {
14133
            // Store locally
14134
90
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
14135
90
            payload.Data = g.DragDropPayloadBufLocal;
14136
90
            memcpy(payload.Data, data, data_size);
14137
90
        }
14138
0
        else
14139
0
        {
14140
0
            payload.Data = NULL;
14141
0
        }
14142
90
        payload.DataSize = (int)data_size;
14143
90
    }
14144
90
    payload.DataFrameCount = g.FrameCount;
14145
14146
    // Return whether the payload has been accepted
14147
90
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
14148
90
}
14149
14150
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
14151
93
{
14152
93
    ImGuiContext& g = *GImGui;
14153
93
    if (!g.DragDropActive)
14154
0
        return false;
14155
14156
93
    ImGuiWindow* window = g.CurrentWindow;
14157
93
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
14158
93
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
14159
93
        return false;
14160
0
    IM_ASSERT(id != 0);
14161
0
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
14162
0
        return false;
14163
0
    if (window->SkipItems)
14164
0
        return false;
14165
14166
0
    IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
14167
0
    g.DragDropTargetRect = bb;
14168
0
    g.DragDropTargetClipRect = window->ClipRect; // May want to be overridden by user depending on use case?
14169
0
    g.DragDropTargetId = id;
14170
0
    g.DragDropWithinTarget = true;
14171
0
    return true;
14172
0
}
14173
14174
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
14175
// 1) we use LastItemData's ImGuiItemStatusFlags_HoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
14176
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
14177
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
14178
bool ImGui::BeginDragDropTarget()
14179
0
{
14180
0
    ImGuiContext& g = *GImGui;
14181
0
    if (!g.DragDropActive)
14182
0
        return false;
14183
14184
0
    ImGuiWindow* window = g.CurrentWindow;
14185
0
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
14186
0
        return false;
14187
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
14188
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
14189
0
        return false;
14190
14191
0
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
14192
0
    ImGuiID id = g.LastItemData.ID;
14193
0
    if (id == 0)
14194
0
    {
14195
0
        id = window->GetIDFromRectangle(display_rect);
14196
0
        KeepAliveID(id);
14197
0
    }
14198
0
    if (g.DragDropPayload.SourceId == id)
14199
0
        return false;
14200
14201
0
    IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
14202
0
    g.DragDropTargetRect = display_rect;
14203
0
    g.DragDropTargetClipRect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasClipRect) ? g.LastItemData.ClipRect : window->ClipRect;
14204
0
    g.DragDropTargetId = id;
14205
0
    g.DragDropWithinTarget = true;
14206
0
    return true;
14207
0
}
14208
14209
bool ImGui::IsDragDropPayloadBeingAccepted()
14210
2
{
14211
2
    ImGuiContext& g = *GImGui;
14212
2
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
14213
2
}
14214
14215
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
14216
0
{
14217
0
    ImGuiContext& g = *GImGui;
14218
0
    ImGuiPayload& payload = g.DragDropPayload;
14219
0
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
14220
0
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
14221
0
    if (type != NULL && !payload.IsDataType(type))
14222
0
        return NULL;
14223
14224
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
14225
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
14226
0
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
14227
0
    ImRect r = g.DragDropTargetRect;
14228
0
    float r_surface = r.GetWidth() * r.GetHeight();
14229
0
    if (r_surface > g.DragDropAcceptIdCurrRectSurface)
14230
0
        return NULL;
14231
14232
0
    g.DragDropAcceptFlags = flags;
14233
0
    g.DragDropAcceptIdCurr = g.DragDropTargetId;
14234
0
    g.DragDropAcceptIdCurrRectSurface = r_surface;
14235
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
14236
14237
    // Render default drop visuals
14238
0
    payload.Preview = was_accepted_previously;
14239
0
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
14240
0
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
14241
0
        RenderDragDropTargetRect(r, g.DragDropTargetClipRect);
14242
14243
0
    g.DragDropAcceptFrameCount = g.FrameCount;
14244
0
    if ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) && g.DragDropMouseButton == -1)
14245
0
        payload.Delivery = was_accepted_previously && (g.DragDropSourceFrameCount < g.FrameCount);
14246
0
    else
14247
0
        payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
14248
0
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
14249
0
        return NULL;
14250
14251
0
    if (payload.Delivery)
14252
0
        IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] AcceptDragDropPayload(): 0x%08X: payload delivery\n", g.DragDropTargetId);
14253
0
    return &payload;
14254
0
}
14255
14256
// FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
14257
void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect)
14258
0
{
14259
0
    ImGuiContext& g = *GImGui;
14260
0
    ImGuiWindow* window = g.CurrentWindow;
14261
0
    ImRect bb_display = bb;
14262
0
    bb_display.ClipWith(item_clip_rect); // Clip THEN expand so we have a way to visualize that target is not entirely visible.
14263
0
    bb_display.Expand(3.5f);
14264
0
    bool push_clip_rect = !window->ClipRect.Contains(bb_display);
14265
0
    if (push_clip_rect)
14266
0
        window->DrawList->PushClipRectFullScreen();
14267
0
    window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
14268
0
    if (push_clip_rect)
14269
0
        window->DrawList->PopClipRect();
14270
0
}
14271
14272
const ImGuiPayload* ImGui::GetDragDropPayload()
14273
0
{
14274
0
    ImGuiContext& g = *GImGui;
14275
0
    return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
14276
0
}
14277
14278
void ImGui::EndDragDropTarget()
14279
0
{
14280
0
    ImGuiContext& g = *GImGui;
14281
0
    IM_ASSERT(g.DragDropActive);
14282
0
    IM_ASSERT(g.DragDropWithinTarget);
14283
0
    g.DragDropWithinTarget = false;
14284
14285
    // Clear drag and drop state payload right after delivery
14286
0
    if (g.DragDropPayload.Delivery)
14287
0
        ClearDragDrop();
14288
0
}
14289
14290
//-----------------------------------------------------------------------------
14291
// [SECTION] LOGGING/CAPTURING
14292
//-----------------------------------------------------------------------------
14293
// All text output from the interface can be captured into tty/file/clipboard.
14294
// By default, tree nodes are automatically opened during logging.
14295
//-----------------------------------------------------------------------------
14296
14297
// Pass text data straight to log (without being displayed)
14298
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
14299
0
{
14300
0
    if (g.LogFile)
14301
0
    {
14302
0
        g.LogBuffer.Buf.resize(0);
14303
0
        g.LogBuffer.appendfv(fmt, args);
14304
0
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
14305
0
    }
14306
0
    else
14307
0
    {
14308
0
        g.LogBuffer.appendfv(fmt, args);
14309
0
    }
14310
0
}
14311
14312
void ImGui::LogText(const char* fmt, ...)
14313
0
{
14314
0
    ImGuiContext& g = *GImGui;
14315
0
    if (!g.LogEnabled)
14316
0
        return;
14317
14318
0
    va_list args;
14319
0
    va_start(args, fmt);
14320
0
    LogTextV(g, fmt, args);
14321
0
    va_end(args);
14322
0
}
14323
14324
void ImGui::LogTextV(const char* fmt, va_list args)
14325
0
{
14326
0
    ImGuiContext& g = *GImGui;
14327
0
    if (!g.LogEnabled)
14328
0
        return;
14329
14330
0
    LogTextV(g, fmt, args);
14331
0
}
14332
14333
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
14334
// We split text into individual lines to add current tree level padding
14335
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
14336
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
14337
0
{
14338
0
    ImGuiContext& g = *GImGui;
14339
0
    ImGuiWindow* window = g.CurrentWindow;
14340
14341
0
    const char* prefix = g.LogNextPrefix;
14342
0
    const char* suffix = g.LogNextSuffix;
14343
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
14344
14345
0
    if (!text_end)
14346
0
        text_end = FindRenderedTextEnd(text, text_end);
14347
14348
0
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
14349
0
    if (ref_pos)
14350
0
        g.LogLinePosY = ref_pos->y;
14351
0
    if (log_new_line)
14352
0
    {
14353
0
        LogText(IM_NEWLINE);
14354
0
        g.LogLineFirstItem = true;
14355
0
    }
14356
14357
0
    if (prefix)
14358
0
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
14359
14360
    // Re-adjust padding if we have popped out of our starting depth
14361
0
    if (g.LogDepthRef > window->DC.TreeDepth)
14362
0
        g.LogDepthRef = window->DC.TreeDepth;
14363
0
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
14364
14365
0
    const char* text_remaining = text;
14366
0
    for (;;)
14367
0
    {
14368
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
14369
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
14370
0
        const char* line_start = text_remaining;
14371
0
        const char* line_end = ImStreolRange(line_start, text_end);
14372
0
        const bool is_last_line = (line_end == text_end);
14373
0
        if (line_start != line_end || !is_last_line)
14374
0
        {
14375
0
            const int line_length = (int)(line_end - line_start);
14376
0
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
14377
0
            LogText("%*s%.*s", indentation, "", line_length, line_start);
14378
0
            g.LogLineFirstItem = false;
14379
0
            if (*line_end == '\n')
14380
0
            {
14381
0
                LogText(IM_NEWLINE);
14382
0
                g.LogLineFirstItem = true;
14383
0
            }
14384
0
        }
14385
0
        if (is_last_line)
14386
0
            break;
14387
0
        text_remaining = line_end + 1;
14388
0
    }
14389
14390
0
    if (suffix)
14391
0
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
14392
0
}
14393
14394
// Start logging/capturing text output
14395
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
14396
0
{
14397
0
    ImGuiContext& g = *GImGui;
14398
0
    ImGuiWindow* window = g.CurrentWindow;
14399
0
    IM_ASSERT(g.LogEnabled == false);
14400
0
    IM_ASSERT(g.LogFile == NULL);
14401
0
    IM_ASSERT(g.LogBuffer.empty());
14402
0
    g.LogEnabled = g.ItemUnclipByLog = true;
14403
0
    g.LogType = type;
14404
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
14405
0
    g.LogDepthRef = window->DC.TreeDepth;
14406
0
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
14407
0
    g.LogLinePosY = FLT_MAX;
14408
0
    g.LogLineFirstItem = true;
14409
0
}
14410
14411
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
14412
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
14413
0
{
14414
0
    ImGuiContext& g = *GImGui;
14415
0
    g.LogNextPrefix = prefix;
14416
0
    g.LogNextSuffix = suffix;
14417
0
}
14418
14419
void ImGui::LogToTTY(int auto_open_depth)
14420
0
{
14421
0
    ImGuiContext& g = *GImGui;
14422
0
    if (g.LogEnabled)
14423
0
        return;
14424
0
    IM_UNUSED(auto_open_depth);
14425
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14426
0
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
14427
0
    g.LogFile = stdout;
14428
0
#endif
14429
0
}
14430
14431
// Start logging/capturing text output to given file
14432
void ImGui::LogToFile(int auto_open_depth, const char* filename)
14433
0
{
14434
0
    ImGuiContext& g = *GImGui;
14435
0
    if (g.LogEnabled)
14436
0
        return;
14437
14438
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
14439
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
14440
    // By opening the file in binary mode "ab" we have consistent output everywhere.
14441
0
    if (!filename)
14442
0
        filename = g.IO.LogFilename;
14443
0
    if (!filename || !filename[0])
14444
0
        return;
14445
0
    ImFileHandle f = ImFileOpen(filename, "ab");
14446
0
    if (!f)
14447
0
    {
14448
0
        IM_ASSERT(0);
14449
0
        return;
14450
0
    }
14451
14452
0
    LogBegin(ImGuiLogType_File, auto_open_depth);
14453
0
    g.LogFile = f;
14454
0
}
14455
14456
// Start logging/capturing text output to clipboard
14457
void ImGui::LogToClipboard(int auto_open_depth)
14458
0
{
14459
0
    ImGuiContext& g = *GImGui;
14460
0
    if (g.LogEnabled)
14461
0
        return;
14462
0
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
14463
0
}
14464
14465
void ImGui::LogToBuffer(int auto_open_depth)
14466
0
{
14467
0
    ImGuiContext& g = *GImGui;
14468
0
    if (g.LogEnabled)
14469
0
        return;
14470
0
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
14471
0
}
14472
14473
void ImGui::LogFinish()
14474
116k
{
14475
116k
    ImGuiContext& g = *GImGui;
14476
116k
    if (!g.LogEnabled)
14477
116k
        return;
14478
14479
0
    LogText(IM_NEWLINE);
14480
0
    switch (g.LogType)
14481
0
    {
14482
0
    case ImGuiLogType_TTY:
14483
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14484
0
        fflush(g.LogFile);
14485
0
#endif
14486
0
        break;
14487
0
    case ImGuiLogType_File:
14488
0
        ImFileClose(g.LogFile);
14489
0
        break;
14490
0
    case ImGuiLogType_Buffer:
14491
0
        break;
14492
0
    case ImGuiLogType_Clipboard:
14493
0
        if (!g.LogBuffer.empty())
14494
0
            SetClipboardText(g.LogBuffer.begin());
14495
0
        break;
14496
0
    case ImGuiLogType_None:
14497
0
        IM_ASSERT(0);
14498
0
        break;
14499
0
    }
14500
14501
0
    g.LogEnabled = g.ItemUnclipByLog = false;
14502
0
    g.LogType = ImGuiLogType_None;
14503
0
    g.LogFile = NULL;
14504
0
    g.LogBuffer.clear();
14505
0
}
14506
14507
// Helper to display logging buttons
14508
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
14509
void ImGui::LogButtons()
14510
0
{
14511
0
    ImGuiContext& g = *GImGui;
14512
14513
0
    PushID("LogButtons");
14514
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14515
0
    const bool log_to_tty = Button("Log To TTY"); SameLine();
14516
#else
14517
    const bool log_to_tty = false;
14518
#endif
14519
0
    const bool log_to_file = Button("Log To File"); SameLine();
14520
0
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
14521
0
    PushItemFlag(ImGuiItemFlags_NoTabStop, true);
14522
0
    SetNextItemWidth(80.0f);
14523
0
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
14524
0
    PopItemFlag();
14525
0
    PopID();
14526
14527
    // Start logging at the end of the function so that the buttons don't appear in the log
14528
0
    if (log_to_tty)
14529
0
        LogToTTY();
14530
0
    if (log_to_file)
14531
0
        LogToFile();
14532
0
    if (log_to_clipboard)
14533
0
        LogToClipboard();
14534
0
}
14535
14536
14537
//-----------------------------------------------------------------------------
14538
// [SECTION] SETTINGS
14539
//-----------------------------------------------------------------------------
14540
// - UpdateSettings() [Internal]
14541
// - MarkIniSettingsDirty() [Internal]
14542
// - FindSettingsHandler() [Internal]
14543
// - ClearIniSettings() [Internal]
14544
// - LoadIniSettingsFromDisk()
14545
// - LoadIniSettingsFromMemory()
14546
// - SaveIniSettingsToDisk()
14547
// - SaveIniSettingsToMemory()
14548
//-----------------------------------------------------------------------------
14549
// - CreateNewWindowSettings() [Internal]
14550
// - FindWindowSettingsByID() [Internal]
14551
// - FindWindowSettingsByWindow() [Internal]
14552
// - ClearWindowSettings() [Internal]
14553
// - WindowSettingsHandler_***() [Internal]
14554
//-----------------------------------------------------------------------------
14555
14556
// Called by NewFrame()
14557
void ImGui::UpdateSettings()
14558
58.4k
{
14559
    // Load settings on first frame (if not explicitly loaded manually before)
14560
58.4k
    ImGuiContext& g = *GImGui;
14561
58.4k
    if (!g.SettingsLoaded)
14562
1
    {
14563
1
        IM_ASSERT(g.SettingsWindows.empty());
14564
1
        if (g.IO.IniFilename)
14565
0
            LoadIniSettingsFromDisk(g.IO.IniFilename);
14566
1
        g.SettingsLoaded = true;
14567
1
    }
14568
14569
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
14570
58.4k
    if (g.SettingsDirtyTimer > 0.0f)
14571
600
    {
14572
600
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
14573
600
        if (g.SettingsDirtyTimer <= 0.0f)
14574
2
        {
14575
2
            if (g.IO.IniFilename != NULL)
14576
0
                SaveIniSettingsToDisk(g.IO.IniFilename);
14577
2
            else
14578
2
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
14579
2
            g.SettingsDirtyTimer = 0.0f;
14580
2
        }
14581
600
    }
14582
58.4k
}
14583
14584
void ImGui::MarkIniSettingsDirty()
14585
0
{
14586
0
    ImGuiContext& g = *GImGui;
14587
0
    if (g.SettingsDirtyTimer <= 0.0f)
14588
0
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
14589
0
}
14590
14591
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
14592
10.2k
{
14593
10.2k
    ImGuiContext& g = *GImGui;
14594
10.2k
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
14595
57
        if (g.SettingsDirtyTimer <= 0.0f)
14596
2
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
14597
10.2k
}
14598
14599
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
14600
2
{
14601
2
    ImGuiContext& g = *GImGui;
14602
2
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
14603
2
    g.SettingsHandlers.push_back(*handler);
14604
2
}
14605
14606
void ImGui::RemoveSettingsHandler(const char* type_name)
14607
0
{
14608
0
    ImGuiContext& g = *GImGui;
14609
0
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
14610
0
        g.SettingsHandlers.erase(handler);
14611
0
}
14612
14613
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
14614
2
{
14615
2
    ImGuiContext& g = *GImGui;
14616
2
    const ImGuiID type_hash = ImHashStr(type_name);
14617
2
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14618
1
        if (handler.TypeHash == type_hash)
14619
0
            return &handler;
14620
2
    return NULL;
14621
2
}
14622
14623
// Clear all settings (windows, tables, docking etc.)
14624
void ImGui::ClearIniSettings()
14625
0
{
14626
0
    ImGuiContext& g = *GImGui;
14627
0
    g.SettingsIniData.clear();
14628
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14629
0
        if (handler.ClearAllFn != NULL)
14630
0
            handler.ClearAllFn(&g, &handler);
14631
0
}
14632
14633
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
14634
0
{
14635
0
    size_t file_data_size = 0;
14636
0
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
14637
0
    if (!file_data)
14638
0
        return;
14639
0
    if (file_data_size > 0)
14640
0
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
14641
0
    IM_FREE(file_data);
14642
0
}
14643
14644
// Zero-tolerance, no error reporting, cheap .ini parsing
14645
// Set ini_size==0 to let us use strlen(ini_data). Do not call this function with a 0 if your buffer is actually empty!
14646
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
14647
0
{
14648
0
    ImGuiContext& g = *GImGui;
14649
0
    IM_ASSERT(g.Initialized);
14650
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
14651
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
14652
14653
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
14654
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
14655
0
    if (ini_size == 0)
14656
0
        ini_size = strlen(ini_data);
14657
0
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
14658
0
    char* const buf = g.SettingsIniData.Buf.Data;
14659
0
    char* const buf_end = buf + ini_size;
14660
0
    memcpy(buf, ini_data, ini_size);
14661
0
    buf_end[0] = 0;
14662
14663
    // Call pre-read handlers
14664
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
14665
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14666
0
        if (handler.ReadInitFn != NULL)
14667
0
            handler.ReadInitFn(&g, &handler);
14668
14669
0
    void* entry_data = NULL;
14670
0
    ImGuiSettingsHandler* entry_handler = NULL;
14671
14672
0
    char* line_end = NULL;
14673
0
    for (char* line = buf; line < buf_end; line = line_end + 1)
14674
0
    {
14675
        // Skip new lines markers, then find end of the line
14676
0
        while (*line == '\n' || *line == '\r')
14677
0
            line++;
14678
0
        line_end = line;
14679
0
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
14680
0
            line_end++;
14681
0
        line_end[0] = 0;
14682
0
        if (line[0] == ';')
14683
0
            continue;
14684
0
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
14685
0
        {
14686
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
14687
0
            line_end[-1] = 0;
14688
0
            const char* name_end = line_end - 1;
14689
0
            const char* type_start = line + 1;
14690
0
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
14691
0
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
14692
0
            if (!type_end || !name_start)
14693
0
                continue;
14694
0
            *type_end = 0; // Overwrite first ']'
14695
0
            name_start++;  // Skip second '['
14696
0
            entry_handler = FindSettingsHandler(type_start);
14697
0
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
14698
0
        }
14699
0
        else if (entry_handler != NULL && entry_data != NULL)
14700
0
        {
14701
            // Let type handler parse the line
14702
0
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
14703
0
        }
14704
0
    }
14705
0
    g.SettingsLoaded = true;
14706
14707
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
14708
0
    memcpy(buf, ini_data, ini_size);
14709
14710
    // Call post-read handlers
14711
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14712
0
        if (handler.ApplyAllFn != NULL)
14713
0
            handler.ApplyAllFn(&g, &handler);
14714
0
}
14715
14716
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
14717
0
{
14718
0
    ImGuiContext& g = *GImGui;
14719
0
    g.SettingsDirtyTimer = 0.0f;
14720
0
    if (!ini_filename)
14721
0
        return;
14722
14723
0
    size_t ini_data_size = 0;
14724
0
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
14725
0
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
14726
0
    if (!f)
14727
0
        return;
14728
0
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
14729
0
    ImFileClose(f);
14730
0
}
14731
14732
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
14733
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
14734
0
{
14735
0
    ImGuiContext& g = *GImGui;
14736
0
    g.SettingsDirtyTimer = 0.0f;
14737
0
    g.SettingsIniData.Buf.resize(0);
14738
0
    g.SettingsIniData.Buf.push_back(0);
14739
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14740
0
        handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
14741
0
    if (out_size)
14742
0
        *out_size = (size_t)g.SettingsIniData.size();
14743
0
    return g.SettingsIniData.c_str();
14744
0
}
14745
14746
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
14747
0
{
14748
0
    ImGuiContext& g = *GImGui;
14749
14750
0
    if (g.IO.ConfigDebugIniSettings == false)
14751
0
    {
14752
        // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
14753
        // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
14754
0
        if (const char* p = strstr(name, "###"))
14755
0
            name = p;
14756
0
    }
14757
0
    const size_t name_len = strlen(name);
14758
14759
    // Allocate chunk
14760
0
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
14761
0
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
14762
0
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
14763
0
    settings->ID = ImHashStr(name, name_len);
14764
0
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
14765
14766
0
    return settings;
14767
0
}
14768
14769
// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
14770
// This is called once per window .ini entry + once per newly instantiated window.
14771
ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
14772
2
{
14773
2
    ImGuiContext& g = *GImGui;
14774
2
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14775
0
        if (settings->ID == id && !settings->WantDelete)
14776
0
            return settings;
14777
2
    return NULL;
14778
2
}
14779
14780
// This is faster if you are holding on a Window already as we don't need to perform a search.
14781
ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
14782
2
{
14783
2
    ImGuiContext& g = *GImGui;
14784
2
    if (window->SettingsOffset != -1)
14785
0
        return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
14786
2
    return FindWindowSettingsByID(window->ID);
14787
2
}
14788
14789
// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
14790
void ImGui::ClearWindowSettings(const char* name)
14791
0
{
14792
    //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
14793
0
    ImGuiContext& g = *GImGui;
14794
0
    ImGuiWindow* window = FindWindowByName(name);
14795
0
    if (window != NULL)
14796
0
    {
14797
0
        window->Flags |= ImGuiWindowFlags_NoSavedSettings;
14798
0
        InitOrLoadWindowSettings(window, NULL);
14799
0
        if (window->DockId != 0)
14800
0
            DockContextProcessUndockWindow(&g, window, true);
14801
0
    }
14802
0
    if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
14803
0
        settings->WantDelete = true;
14804
0
}
14805
14806
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14807
0
{
14808
0
    ImGuiContext& g = *ctx;
14809
0
    for (ImGuiWindow* window : g.Windows)
14810
0
        window->SettingsOffset = -1;
14811
0
    g.SettingsWindows.clear();
14812
0
}
14813
14814
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
14815
0
{
14816
0
    ImGuiID id = ImHashStr(name);
14817
0
    ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
14818
0
    if (settings)
14819
0
        *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
14820
0
    else
14821
0
        settings = ImGui::CreateNewWindowSettings(name);
14822
0
    settings->ID = id;
14823
0
    settings->WantApply = true;
14824
0
    return (void*)settings;
14825
0
}
14826
14827
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
14828
0
{
14829
0
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
14830
0
    int x, y;
14831
0
    int i;
14832
0
    ImU32 u1;
14833
0
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
14834
0
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
14835
0
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
14836
0
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
14837
0
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
14838
0
    else if (sscanf(line, "IsChild=%d", &i) == 1)           { settings->IsChild = (i != 0); }
14839
0
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
14840
0
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
14841
0
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
14842
0
}
14843
14844
// Apply to existing windows (if any)
14845
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14846
0
{
14847
0
    ImGuiContext& g = *ctx;
14848
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14849
0
        if (settings->WantApply)
14850
0
        {
14851
0
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
14852
0
                ApplyWindowSettings(window, settings);
14853
0
            settings->WantApply = false;
14854
0
        }
14855
0
}
14856
14857
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
14858
0
{
14859
    // Gather data from windows that were active during this session
14860
    // (if a window wasn't opened in this session we preserve its settings)
14861
0
    ImGuiContext& g = *ctx;
14862
0
    for (ImGuiWindow* window : g.Windows)
14863
0
    {
14864
0
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
14865
0
            continue;
14866
14867
0
        ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
14868
0
        if (!settings)
14869
0
        {
14870
0
            settings = ImGui::CreateNewWindowSettings(window->Name);
14871
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
14872
0
        }
14873
0
        IM_ASSERT(settings->ID == window->ID);
14874
0
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
14875
0
        settings->Size = ImVec2ih(window->SizeFull);
14876
0
        settings->ViewportId = window->ViewportId;
14877
0
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
14878
0
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
14879
0
        settings->DockId = window->DockId;
14880
0
        settings->ClassId = window->WindowClass.ClassId;
14881
0
        settings->DockOrder = window->DockOrder;
14882
0
        settings->Collapsed = window->Collapsed;
14883
0
        settings->IsChild = (window->RootWindow != window); // Cannot rely on ImGuiWindowFlags_ChildWindow here as docked windows have this set.
14884
0
        settings->WantDelete = false;
14885
0
    }
14886
14887
    // Write to text buffer
14888
0
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
14889
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14890
0
    {
14891
0
        if (settings->WantDelete)
14892
0
            continue;
14893
0
        const char* settings_name = settings->GetName();
14894
0
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
14895
0
        if (settings->IsChild)
14896
0
        {
14897
0
            buf->appendf("IsChild=1\n");
14898
0
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14899
0
        }
14900
0
        else
14901
0
        {
14902
0
            if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14903
0
            {
14904
0
                buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
14905
0
                buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
14906
0
            }
14907
0
            if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14908
0
                buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
14909
0
            if (settings->Size.x != 0 || settings->Size.y != 0)
14910
0
                buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14911
0
            buf->appendf("Collapsed=%d\n", settings->Collapsed);
14912
0
            if (settings->DockId != 0)
14913
0
            {
14914
                //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
14915
0
                if (settings->DockOrder == -1)
14916
0
                    buf->appendf("DockId=0x%08X\n", settings->DockId);
14917
0
                else
14918
0
                    buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
14919
0
                if (settings->ClassId != 0)
14920
0
                    buf->appendf("ClassId=0x%08X\n", settings->ClassId);
14921
0
            }
14922
0
        }
14923
0
        buf->append("\n");
14924
0
    }
14925
0
}
14926
14927
14928
//-----------------------------------------------------------------------------
14929
// [SECTION] LOCALIZATION
14930
//-----------------------------------------------------------------------------
14931
14932
void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
14933
1
{
14934
1
    ImGuiContext& g = *GImGui;
14935
13
    for (int n = 0; n < count; n++)
14936
12
        g.LocalizationTable[entries[n].Key] = entries[n].Text;
14937
1
}
14938
14939
14940
//-----------------------------------------------------------------------------
14941
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
14942
//-----------------------------------------------------------------------------
14943
// - GetMainViewport()
14944
// - FindViewportByID()
14945
// - FindViewportByPlatformHandle()
14946
// - SetCurrentViewport() [Internal]
14947
// - SetWindowViewport() [Internal]
14948
// - GetWindowAlwaysWantOwnViewport() [Internal]
14949
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
14950
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
14951
// - TranslateWindowsInViewport() [Internal]
14952
// - ScaleWindowsInViewport() [Internal]
14953
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
14954
// - UpdateViewportsNewFrame() [Internal]
14955
// - UpdateViewportsEndFrame() [Internal]
14956
// - AddUpdateViewport() [Internal]
14957
// - WindowSelectViewport() [Internal]
14958
// - WindowSyncOwnedViewport() [Internal]
14959
// - UpdatePlatformWindows()
14960
// - RenderPlatformWindowsDefault()
14961
// - FindPlatformMonitorForPos() [Internal]
14962
// - FindPlatformMonitorForRect() [Internal]
14963
// - UpdateViewportPlatformMonitor() [Internal]
14964
// - DestroyPlatformWindow() [Internal]
14965
// - DestroyPlatformWindows()
14966
//-----------------------------------------------------------------------------
14967
14968
ImGuiViewport* ImGui::GetMainViewport()
14969
244k
{
14970
244k
    ImGuiContext& g = *GImGui;
14971
244k
    return g.Viewports[0];
14972
244k
}
14973
14974
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
14975
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
14976
58.4k
{
14977
58.4k
    ImGuiContext& g = *GImGui;
14978
58.4k
    for (ImGuiViewportP* viewport : g.Viewports)
14979
58.4k
        if (viewport->ID == id)
14980
58.4k
            return viewport;
14981
0
    return NULL;
14982
58.4k
}
14983
14984
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
14985
0
{
14986
0
    ImGuiContext& g = *GImGui;
14987
0
    for (ImGuiViewportP* viewport : g.Viewports)
14988
0
        if (viewport->PlatformHandle == platform_handle)
14989
0
            return viewport;
14990
0
    return NULL;
14991
0
}
14992
14993
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
14994
254k
{
14995
254k
    ImGuiContext& g = *GImGui;
14996
254k
    (void)current_window;
14997
14998
254k
    if (viewport)
14999
195k
        viewport->LastFrameActive = g.FrameCount;
15000
254k
    if (g.CurrentViewport == viewport)
15001
137k
        return;
15002
116k
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
15003
116k
    g.CurrentViewport = viewport;
15004
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
15005
15006
    // Notify platform layer of viewport changes
15007
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
15008
116k
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
15009
0
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
15010
116k
}
15011
15012
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
15013
127k
{
15014
    // Abandon viewport
15015
127k
    if (window->ViewportOwned && window->Viewport->Window == window)
15016
0
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
15017
15018
127k
    window->Viewport = viewport;
15019
127k
    window->ViewportId = viewport->ID;
15020
127k
    window->ViewportOwned = (viewport->Window == window);
15021
127k
}
15022
15023
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
15024
0
{
15025
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
15026
0
    ImGuiContext& g = *GImGui;
15027
0
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
15028
0
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
15029
0
            if (!window->DockIsActive)
15030
0
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
15031
0
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
15032
0
                        return true;
15033
0
    return false;
15034
0
}
15035
15036
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
15037
0
{
15038
0
    ImGuiContext& g = *GImGui;
15039
0
    if (window->Viewport == viewport)
15040
0
        return false;
15041
0
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
15042
0
        return false;
15043
0
    if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
15044
0
        return false;
15045
0
    if (!viewport->GetMainRect().Contains(window->Rect()))
15046
0
        return false;
15047
0
    if (GetWindowAlwaysWantOwnViewport(window))
15048
0
        return false;
15049
15050
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
15051
0
    for (ImGuiWindow* window_behind : g.Windows)
15052
0
    {
15053
0
        if (window_behind == window)
15054
0
            break;
15055
0
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
15056
0
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
15057
0
                return false;
15058
0
    }
15059
15060
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
15061
0
    ImGuiViewportP* old_viewport = window->Viewport;
15062
0
    if (window->ViewportOwned)
15063
0
        for (int n = 0; n < g.Windows.Size; n++)
15064
0
            if (g.Windows[n]->Viewport == old_viewport)
15065
0
                SetWindowViewport(g.Windows[n], viewport);
15066
0
    SetWindowViewport(window, viewport);
15067
0
    BringWindowToDisplayFront(window);
15068
15069
0
    return true;
15070
0
}
15071
15072
// FIXME: handle 0 to N host viewports
15073
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
15074
0
{
15075
0
    ImGuiContext& g = *GImGui;
15076
0
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
15077
0
}
15078
15079
// Translate Dear ImGui windows when a Host Viewport has been moved
15080
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
15081
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
15082
0
{
15083
0
    ImGuiContext& g = *GImGui;
15084
0
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
15085
15086
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
15087
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
15088
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
15089
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
15090
    // and so the window will appear to teleport when releasing the mouse.
15091
0
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
15092
0
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
15093
0
    ImVec2 delta_pos = new_pos - old_pos;
15094
0
    for (ImGuiWindow* window : g.Windows) // FIXME-OPT
15095
0
        if (translate_all_windows || (window->Viewport == viewport && test_still_fit_rect.Contains(window->Rect())))
15096
0
            TranslateWindow(window, delta_pos);
15097
0
}
15098
15099
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
15100
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
15101
0
{
15102
0
    ImGuiContext& g = *GImGui;
15103
0
    if (viewport->Window)
15104
0
    {
15105
0
        ScaleWindow(viewport->Window, scale);
15106
0
    }
15107
0
    else
15108
0
    {
15109
0
        for (ImGuiWindow* window : g.Windows)
15110
0
            if (window->Viewport == viewport)
15111
0
                ScaleWindow(window, scale);
15112
0
    }
15113
0
}
15114
15115
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
15116
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
15117
// B) It requires Platform_GetWindowFocus to be implemented by backend.
15118
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
15119
0
{
15120
0
    ImGuiContext& g = *GImGui;
15121
0
    ImGuiViewportP* best_candidate = NULL;
15122
0
    for (ImGuiViewportP* viewport : g.Viewports)
15123
0
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
15124
0
            if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
15125
0
                best_candidate = viewport;
15126
0
    return best_candidate;
15127
0
}
15128
15129
// Update viewports and monitor infos
15130
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
15131
static void ImGui::UpdateViewportsNewFrame()
15132
58.4k
{
15133
58.4k
    ImGuiContext& g = *GImGui;
15134
58.4k
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
15135
15136
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
15137
    // Update Focused status
15138
58.4k
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
15139
58.4k
    if (viewports_enabled)
15140
0
    {
15141
0
        ImGuiViewportP* focused_viewport = NULL;
15142
0
        for (ImGuiViewportP* viewport : g.Viewports)
15143
0
        {
15144
0
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
15145
0
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
15146
0
            {
15147
0
                bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
15148
0
                if (is_minimized)
15149
0
                    viewport->Flags |= ImGuiViewportFlags_IsMinimized;
15150
0
                else
15151
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
15152
0
            }
15153
15154
            // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
15155
            // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
15156
0
            if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
15157
0
            {
15158
0
                bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
15159
0
                if (is_focused)
15160
0
                    viewport->Flags |= ImGuiViewportFlags_IsFocused;
15161
0
                else
15162
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
15163
0
                if (is_focused)
15164
0
                    focused_viewport = viewport;
15165
0
            }
15166
0
        }
15167
15168
        // Focused viewport has changed?
15169
0
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
15170
0
        {
15171
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X, attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID);
15172
0
            const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId);
15173
0
            const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
15174
15175
            // Store a tag so we can infer z-order easily from all our windows
15176
            // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
15177
            // will keep the front most stamp instead of losing it back to their parent viewport.
15178
0
            if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
15179
0
                focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
15180
0
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
15181
15182
            // Focus associated dear imgui window
15183
            // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
15184
            // - if focus didn't happen because we destroyed another window (#6462)
15185
            // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
15186
0
            const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
15187
0
            if (apply_imgui_focus_on_focused_viewport)
15188
0
            {
15189
0
                focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
15190
0
                ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
15191
0
                if (focused_viewport->Window != NULL)
15192
0
                    FocusWindow(focused_viewport->Window, focus_request_flags);
15193
0
                else if (focused_viewport->LastFocusedHadNavWindow)
15194
0
                    FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport
15195
0
                else
15196
0
                    FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused
15197
0
            }
15198
0
        }
15199
0
        if (focused_viewport)
15200
0
            focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
15201
0
    }
15202
15203
    // Create/update main viewport with current platform position.
15204
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
15205
58.4k
    ImGuiViewportP* main_viewport = g.Viewports[0];
15206
58.4k
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
15207
58.4k
    IM_ASSERT(main_viewport->Window == NULL);
15208
58.4k
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
15209
58.4k
    ImVec2 main_viewport_size = g.IO.DisplaySize;
15210
58.4k
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
15211
0
    {
15212
0
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
15213
0
        main_viewport_size = main_viewport->Size;
15214
0
    }
15215
58.4k
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
15216
15217
58.4k
    g.CurrentDpiScale = 0.0f;
15218
58.4k
    g.CurrentViewport = NULL;
15219
58.4k
    g.MouseViewport = NULL;
15220
116k
    for (int n = 0; n < g.Viewports.Size; n++)
15221
58.4k
    {
15222
58.4k
        ImGuiViewportP* viewport = g.Viewports[n];
15223
58.4k
        viewport->Idx = n;
15224
15225
        // Erase unused viewports
15226
58.4k
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
15227
0
        {
15228
0
            DestroyViewport(viewport);
15229
0
            n--;
15230
0
            continue;
15231
0
        }
15232
15233
58.4k
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
15234
58.4k
        if (viewports_enabled)
15235
0
        {
15236
            // Update Position and Size (from Platform Window to ImGui) if requested.
15237
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
15238
0
            if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
15239
0
            {
15240
                // Viewport->WorkPos and WorkSize will be updated below
15241
0
                if (viewport->PlatformRequestMove)
15242
0
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
15243
0
                if (viewport->PlatformRequestResize)
15244
0
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
15245
0
            }
15246
0
        }
15247
15248
        // Update/copy monitor info
15249
58.4k
        UpdateViewportPlatformMonitor(viewport);
15250
15251
        // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
15252
58.4k
        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
15253
58.4k
        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
15254
58.4k
        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
15255
58.4k
        viewport->UpdateWorkRect();
15256
15257
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
15258
58.4k
        viewport->Alpha = 1.0f;
15259
15260
        // Translate Dear ImGui windows when a Host Viewport has been moved
15261
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
15262
58.4k
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
15263
58.4k
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
15264
0
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
15265
15266
        // Update DPI scale
15267
58.4k
        float new_dpi_scale;
15268
58.4k
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
15269
0
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
15270
58.4k
        else if (viewport->PlatformMonitor != -1)
15271
0
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
15272
58.4k
        else
15273
58.4k
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
15274
58.4k
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
15275
0
        {
15276
0
            float scale_factor = new_dpi_scale / viewport->DpiScale;
15277
0
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
15278
0
                ScaleWindowsInViewport(viewport, scale_factor);
15279
            //if (viewport == GetMainViewport())
15280
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
15281
15282
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
15283
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
15284
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
15285
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
15286
            //    g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor);
15287
0
        }
15288
58.4k
        viewport->DpiScale = new_dpi_scale;
15289
58.4k
    }
15290
15291
    // Update fallback monitor
15292
58.4k
    g.PlatformMonitorsFullWorkRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
15293
58.4k
    if (g.PlatformIO.Monitors.Size == 0)
15294
58.4k
    {
15295
58.4k
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
15296
58.4k
        monitor->MainPos = main_viewport->Pos;
15297
58.4k
        monitor->MainSize = main_viewport->Size;
15298
58.4k
        monitor->WorkPos = main_viewport->WorkPos;
15299
58.4k
        monitor->WorkSize = main_viewport->WorkSize;
15300
58.4k
        monitor->DpiScale = main_viewport->DpiScale;
15301
58.4k
        g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos);
15302
58.4k
        g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos + monitor->WorkSize);
15303
58.4k
    }
15304
58.4k
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
15305
0
    {
15306
0
        g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos);
15307
0
        g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos + monitor.WorkSize);
15308
0
    }
15309
15310
58.4k
    if (!viewports_enabled)
15311
58.4k
    {
15312
58.4k
        g.MouseViewport = main_viewport;
15313
58.4k
        return;
15314
58.4k
    }
15315
15316
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
15317
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
15318
0
    ImGuiViewportP* viewport_hovered = NULL;
15319
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
15320
0
    {
15321
0
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
15322
0
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
15323
0
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
15324
0
    }
15325
0
    else
15326
0
    {
15327
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
15328
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
15329
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
15330
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
15331
0
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
15332
0
    }
15333
0
    if (viewport_hovered != NULL)
15334
0
        g.MouseLastHoveredViewport = viewport_hovered;
15335
0
    else if (g.MouseLastHoveredViewport == NULL)
15336
0
        g.MouseLastHoveredViewport = g.Viewports[0];
15337
15338
    // Update mouse reference viewport
15339
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
15340
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
15341
0
    if (g.MovingWindow && g.MovingWindow->Viewport)
15342
0
        g.MouseViewport = g.MovingWindow->Viewport;
15343
0
    else
15344
0
        g.MouseViewport = g.MouseLastHoveredViewport;
15345
15346
    // When dragging something, always refer to the last hovered viewport.
15347
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
15348
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
15349
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
15350
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
15351
0
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
15352
0
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
15353
0
        viewport_hovered = g.MouseLastHoveredViewport;
15354
0
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
15355
0
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
15356
0
            g.MouseViewport = viewport_hovered;
15357
15358
0
    IM_ASSERT(g.MouseViewport != NULL);
15359
0
}
15360
15361
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
15362
static void ImGui::UpdateViewportsEndFrame()
15363
58.4k
{
15364
58.4k
    ImGuiContext& g = *GImGui;
15365
58.4k
    g.PlatformIO.Viewports.resize(0);
15366
116k
    for (int i = 0; i < g.Viewports.Size; i++)
15367
58.4k
    {
15368
58.4k
        ImGuiViewportP* viewport = g.Viewports[i];
15369
58.4k
        viewport->LastPos = viewport->Pos;
15370
58.4k
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
15371
0
            if (i > 0) // Always include main viewport in the list
15372
0
                continue;
15373
58.4k
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
15374
0
            continue;
15375
58.4k
        if (i > 0)
15376
58.4k
            IM_ASSERT(viewport->Window != NULL);
15377
58.4k
        g.PlatformIO.Viewports.push_back(viewport);
15378
58.4k
    }
15379
58.4k
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
15380
58.4k
}
15381
15382
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
15383
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
15384
58.4k
{
15385
58.4k
    ImGuiContext& g = *GImGui;
15386
58.4k
    IM_ASSERT(id != 0);
15387
15388
58.4k
    flags |= ImGuiViewportFlags_IsPlatformWindow;
15389
58.4k
    if (window != NULL)
15390
0
    {
15391
0
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
15392
0
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
15393
0
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
15394
0
            flags |= ImGuiViewportFlags_NoInputs;
15395
0
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
15396
0
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
15397
0
    }
15398
15399
58.4k
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
15400
58.4k
    if (viewport)
15401
58.4k
    {
15402
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
15403
58.4k
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
15404
58.4k
            viewport->Pos = pos;
15405
58.4k
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
15406
58.4k
            viewport->Size = size;
15407
58.4k
        viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
15408
58.4k
    }
15409
0
    else
15410
0
    {
15411
        // New viewport
15412
0
        viewport = IM_NEW(ImGuiViewportP)();
15413
0
        viewport->ID = id;
15414
0
        viewport->Idx = g.Viewports.Size;
15415
0
        viewport->Pos = viewport->LastPos = pos;
15416
0
        viewport->Size = size;
15417
0
        viewport->Flags = flags;
15418
0
        UpdateViewportPlatformMonitor(viewport);
15419
0
        g.Viewports.push_back(viewport);
15420
0
        g.ViewportCreatedCount++;
15421
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
15422
15423
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
15424
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
15425
0
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
15426
0
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
15427
0
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
15428
0
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
15429
15430
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
15431
        // This is so we can select an appropriate font size on the first frame of our window lifetime
15432
0
        if (viewport->PlatformMonitor != -1)
15433
0
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
15434
0
    }
15435
15436
58.4k
    viewport->Window = window;
15437
58.4k
    viewport->LastFrameActive = g.FrameCount;
15438
58.4k
    viewport->UpdateWorkRect();
15439
58.4k
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
15440
15441
58.4k
    if (window != NULL)
15442
0
        window->ViewportOwned = true;
15443
15444
58.4k
    return viewport;
15445
58.4k
}
15446
15447
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
15448
0
{
15449
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
15450
0
    ImGuiContext& g = *GImGui;
15451
0
    for (ImGuiWindow* window : g.Windows)
15452
0
    {
15453
0
        if (window->Viewport != viewport)
15454
0
            continue;
15455
0
        window->Viewport = NULL;
15456
0
        window->ViewportOwned = false;
15457
0
    }
15458
0
    if (viewport == g.MouseLastHoveredViewport)
15459
0
        g.MouseLastHoveredViewport = NULL;
15460
15461
    // Destroy
15462
0
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15463
0
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
15464
0
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
15465
0
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
15466
0
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
15467
0
    IM_DELETE(viewport);
15468
0
}
15469
15470
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
15471
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
15472
127k
{
15473
127k
    ImGuiContext& g = *GImGui;
15474
127k
    ImGuiWindowFlags flags = window->Flags;
15475
127k
    window->ViewportAllowPlatformMonitorExtend = -1;
15476
15477
    // Restore main viewport if multi-viewport is not supported by the backend
15478
127k
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
15479
127k
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
15480
127k
    {
15481
127k
        SetWindowViewport(window, main_viewport);
15482
127k
        return;
15483
127k
    }
15484
0
    window->ViewportOwned = false;
15485
15486
    // Appearing popups reset their viewport so they can inherit again
15487
0
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
15488
0
    {
15489
0
        window->Viewport = NULL;
15490
0
        window->ViewportId = 0;
15491
0
    }
15492
15493
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
15494
0
    {
15495
        // By default inherit from parent window
15496
0
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
15497
0
            window->Viewport = window->ParentWindow->Viewport;
15498
15499
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
15500
0
        if (window->Viewport == NULL && window->ViewportId != 0)
15501
0
        {
15502
0
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
15503
0
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
15504
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
15505
0
        }
15506
0
    }
15507
15508
0
    bool lock_viewport = false;
15509
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
15510
0
    {
15511
        // Code explicitly request a viewport
15512
0
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
15513
0
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
15514
0
        if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL)
15515
0
        {
15516
0
            window->Viewport->Window = window;
15517
0
            window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node)
15518
0
        }
15519
0
        lock_viewport = true;
15520
0
    }
15521
0
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
15522
0
    {
15523
        // Always inherit viewport from parent window
15524
0
        if (window->DockNode && window->DockNode->HostWindow)
15525
0
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
15526
0
        window->Viewport = window->ParentWindow->Viewport;
15527
0
    }
15528
0
    else if (window->DockNode && window->DockNode->HostWindow)
15529
0
    {
15530
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
15531
0
        window->Viewport = window->DockNode->HostWindow->Viewport;
15532
0
    }
15533
0
    else if (flags & ImGuiWindowFlags_Tooltip)
15534
0
    {
15535
0
        window->Viewport = g.MouseViewport;
15536
0
    }
15537
0
    else if (GetWindowAlwaysWantOwnViewport(window))
15538
0
    {
15539
0
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15540
0
    }
15541
0
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
15542
0
    {
15543
0
        if (window->Viewport != NULL && window->Viewport->Window == window)
15544
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15545
0
    }
15546
0
    else
15547
0
    {
15548
        // Merge into host viewport?
15549
        // We cannot test window->ViewportOwned as it set lower in the function.
15550
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
15551
0
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
15552
0
        if (try_to_merge_into_host_viewport)
15553
0
            UpdateTryMergeWindowIntoHostViewports(window);
15554
0
    }
15555
15556
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
15557
0
    if (window->Viewport == NULL)
15558
0
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
15559
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15560
15561
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
15562
0
    if (!lock_viewport)
15563
0
    {
15564
0
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
15565
0
        {
15566
            // We need to take account of the possibility that mouse may become invalid.
15567
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
15568
0
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
15569
0
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
15570
0
            bool mouse_valid = IsMousePosValid(&mouse_ref);
15571
0
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
15572
0
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
15573
0
            else
15574
0
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
15575
0
        }
15576
0
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
15577
0
        {
15578
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
15579
0
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
15580
0
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
15581
0
            {
15582
                // Steal/transfer ownership
15583
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
15584
0
                window->Viewport->Window = window;
15585
0
                window->Viewport->ID = window->ID;
15586
0
                window->Viewport->LastNameHash = 0;
15587
0
            }
15588
0
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
15589
0
            {
15590
                // New viewport
15591
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
15592
0
            }
15593
0
        }
15594
0
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
15595
0
        {
15596
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
15597
            // Child windows are kept contained within their parent.
15598
0
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
15599
0
        }
15600
0
    }
15601
15602
    // Update flags
15603
0
    window->ViewportOwned = (window == window->Viewport->Window);
15604
0
    window->ViewportId = window->Viewport->ID;
15605
15606
    // If the OS window has a title bar, hide our imgui title bar
15607
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
15608
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
15609
0
}
15610
15611
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
15612
0
{
15613
0
    ImGuiContext& g = *GImGui;
15614
15615
0
    bool viewport_rect_changed = false;
15616
15617
    // Synchronize window --> viewport in most situations
15618
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
15619
0
    if (window->Viewport->PlatformRequestMove)
15620
0
    {
15621
0
        window->Pos = window->Viewport->Pos;
15622
0
        MarkIniSettingsDirty(window);
15623
0
    }
15624
0
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
15625
0
    {
15626
0
        viewport_rect_changed = true;
15627
0
        window->Viewport->Pos = window->Pos;
15628
0
    }
15629
15630
0
    if (window->Viewport->PlatformRequestResize)
15631
0
    {
15632
0
        window->Size = window->SizeFull = window->Viewport->Size;
15633
0
        MarkIniSettingsDirty(window);
15634
0
    }
15635
0
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
15636
0
    {
15637
0
        viewport_rect_changed = true;
15638
0
        window->Viewport->Size = window->Size;
15639
0
    }
15640
0
    window->Viewport->UpdateWorkRect();
15641
15642
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
15643
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
15644
0
    if (viewport_rect_changed)
15645
0
        UpdateViewportPlatformMonitor(window->Viewport);
15646
15647
    // Update common viewport flags
15648
0
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
15649
0
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
15650
0
    ImGuiWindowFlags window_flags = window->Flags;
15651
0
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
15652
0
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
15653
0
    if (window_flags & ImGuiWindowFlags_Tooltip)
15654
0
        viewport_flags |= ImGuiViewportFlags_TopMost;
15655
0
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
15656
0
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
15657
0
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
15658
0
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
15659
15660
    // Not correct to set modal as topmost because:
15661
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
15662
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
15663
    //if (flags & ImGuiWindowFlags_Modal)
15664
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
15665
15666
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
15667
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
15668
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
15669
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
15670
0
    if (is_short_lived_floating_window && !is_modal)
15671
0
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
15672
15673
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
15674
0
    if (window->WindowClass.ViewportFlagsOverrideSet)
15675
0
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
15676
0
    if (window->WindowClass.ViewportFlagsOverrideClear)
15677
0
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
15678
15679
    // We can also tell the backend that clearing the platform window won't be necessary,
15680
    // as our window background is filling the viewport and we have disabled BgAlpha.
15681
    // FIXME: Work on support for per-viewport transparency (#2766)
15682
0
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
15683
0
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
15684
15685
0
    window->Viewport->Flags = viewport_flags;
15686
15687
    // Update parent viewport ID
15688
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
15689
0
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
15690
0
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
15691
0
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
15692
0
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
15693
0
    else
15694
0
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
15695
0
}
15696
15697
// Called by user at the end of the main loop, after EndFrame()
15698
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
15699
void ImGui::UpdatePlatformWindows()
15700
0
{
15701
0
    ImGuiContext& g = *GImGui;
15702
0
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
15703
0
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
15704
0
    g.FrameCountPlatformEnded = g.FrameCount;
15705
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
15706
0
        return;
15707
15708
    // Create/resize/destroy platform windows to match each active viewport.
15709
    // Skip the main viewport (index 0), which is always fully handled by the application!
15710
0
    for (int i = 1; i < g.Viewports.Size; i++)
15711
0
    {
15712
0
        ImGuiViewportP* viewport = g.Viewports[i];
15713
15714
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
15715
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
15716
0
        bool destroy_platform_window = false;
15717
0
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
15718
0
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
15719
0
        if (destroy_platform_window)
15720
0
        {
15721
0
            DestroyPlatformWindow(viewport);
15722
0
            continue;
15723
0
        }
15724
15725
        // New windows that appears directly in a new viewport won't always have a size on their first frame
15726
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
15727
0
            continue;
15728
15729
        // Create window
15730
0
        const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
15731
0
        if (is_new_platform_window)
15732
0
        {
15733
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15734
0
            g.PlatformIO.Platform_CreateWindow(viewport);
15735
0
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
15736
0
                g.PlatformIO.Renderer_CreateWindow(viewport);
15737
0
            g.PlatformWindowsCreatedCount++;
15738
0
            viewport->LastNameHash = 0;
15739
0
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
15740
0
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
15741
0
            viewport->PlatformWindowCreated = true;
15742
0
        }
15743
15744
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
15745
0
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
15746
0
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
15747
0
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
15748
0
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
15749
0
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
15750
0
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
15751
0
        viewport->LastPlatformPos = viewport->Pos;
15752
0
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
15753
15754
        // Update title bar (if it changed)
15755
0
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
15756
0
        {
15757
0
            const char* title_begin = window_for_title->Name;
15758
0
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
15759
0
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
15760
0
            if (viewport->LastNameHash != title_hash)
15761
0
            {
15762
0
                char title_end_backup_c = *title_end;
15763
0
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
15764
0
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
15765
0
                *title_end = title_end_backup_c;
15766
0
                viewport->LastNameHash = title_hash;
15767
0
            }
15768
0
        }
15769
15770
        // Update alpha (if it changed)
15771
0
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
15772
0
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
15773
0
        viewport->LastAlpha = viewport->Alpha;
15774
15775
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
15776
0
        if (g.PlatformIO.Platform_UpdateWindow)
15777
0
            g.PlatformIO.Platform_UpdateWindow(viewport);
15778
15779
0
        if (is_new_platform_window)
15780
0
        {
15781
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
15782
0
            if (g.FrameCount < 3)
15783
0
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
15784
15785
            // Show window
15786
0
            g.PlatformIO.Platform_ShowWindow(viewport);
15787
15788
            // Even without focus, we assume the window becomes front-most.
15789
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
15790
0
            if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
15791
0
                viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
15792
0
        }
15793
15794
        // Clear request flags
15795
0
        viewport->ClearRequestFlags();
15796
0
    }
15797
0
}
15798
15799
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
15800
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
15801
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
15802
//
15803
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15804
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15805
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15806
//            MyRenderFunction(platform_io.Viewports[i], my_args);
15807
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15808
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15809
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
15810
//
15811
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
15812
0
{
15813
    // Skip the main viewport (index 0), which is always fully handled by the application!
15814
0
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15815
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15816
0
    {
15817
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15818
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15819
0
            continue;
15820
0
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
15821
0
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
15822
0
    }
15823
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15824
0
    {
15825
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15826
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15827
0
            continue;
15828
0
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
15829
0
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
15830
0
    }
15831
0
}
15832
15833
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
15834
0
{
15835
0
    ImGuiContext& g = *GImGui;
15836
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
15837
0
    {
15838
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15839
0
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
15840
0
            return monitor_n;
15841
0
    }
15842
0
    return -1;
15843
0
}
15844
15845
// Search for the monitor with the largest intersection area with the given rectangle
15846
// We generally try to avoid searching loops but the monitor count should be very small here
15847
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
15848
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
15849
58.4k
{
15850
58.4k
    ImGuiContext& g = *GImGui;
15851
15852
58.4k
    const int monitor_count = g.PlatformIO.Monitors.Size;
15853
58.4k
    if (monitor_count <= 1)
15854
58.4k
        return monitor_count - 1;
15855
15856
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
15857
    // This is necessary for tooltips which always resize down to zero at first.
15858
0
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
15859
0
    int best_monitor_n = -1;
15860
0
    float best_monitor_surface = 0.001f;
15861
15862
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
15863
0
    {
15864
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15865
0
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
15866
0
        if (monitor_rect.Contains(rect))
15867
0
            return monitor_n;
15868
0
        ImRect overlapping_rect = rect;
15869
0
        overlapping_rect.ClipWithFull(monitor_rect);
15870
0
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
15871
0
        if (overlapping_surface < best_monitor_surface)
15872
0
            continue;
15873
0
        best_monitor_surface = overlapping_surface;
15874
0
        best_monitor_n = monitor_n;
15875
0
    }
15876
0
    return best_monitor_n;
15877
0
}
15878
15879
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
15880
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
15881
58.4k
{
15882
58.4k
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
15883
58.4k
}
15884
15885
// Return value is always != NULL, but don't hold on it across frames.
15886
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
15887
0
{
15888
0
    ImGuiContext& g = *GImGui;
15889
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
15890
0
    int monitor_idx = viewport->PlatformMonitor;
15891
0
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
15892
0
        return &g.PlatformIO.Monitors[monitor_idx];
15893
0
    return &g.FallbackMonitor;
15894
0
}
15895
15896
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
15897
0
{
15898
0
    ImGuiContext& g = *GImGui;
15899
0
    if (viewport->PlatformWindowCreated)
15900
0
    {
15901
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15902
0
        if (g.PlatformIO.Renderer_DestroyWindow)
15903
0
            g.PlatformIO.Renderer_DestroyWindow(viewport);
15904
0
        if (g.PlatformIO.Platform_DestroyWindow)
15905
0
            g.PlatformIO.Platform_DestroyWindow(viewport);
15906
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
15907
15908
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
15909
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
15910
0
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
15911
0
            viewport->PlatformWindowCreated = false;
15912
0
    }
15913
0
    else
15914
0
    {
15915
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
15916
0
    }
15917
0
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
15918
0
    viewport->ClearRequestFlags();
15919
0
}
15920
15921
void ImGui::DestroyPlatformWindows()
15922
0
{
15923
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
15924
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
15925
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
15926
    // code to operator a consistent manner.
15927
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
15928
    // crashing if it doesn't have data stored.
15929
0
    ImGuiContext& g = *GImGui;
15930
0
    for (ImGuiViewportP* viewport : g.Viewports)
15931
0
        DestroyPlatformWindow(viewport);
15932
0
}
15933
15934
15935
//-----------------------------------------------------------------------------
15936
// [SECTION] DOCKING
15937
//-----------------------------------------------------------------------------
15938
// Docking: Internal Types
15939
// Docking: Forward Declarations
15940
// Docking: ImGuiDockContext
15941
// Docking: ImGuiDockContext Docking/Undocking functions
15942
// Docking: ImGuiDockNode
15943
// Docking: ImGuiDockNode Tree manipulation functions
15944
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
15945
// Docking: Builder Functions
15946
// Docking: Begin/End Support Functions (called from Begin/End)
15947
// Docking: Settings
15948
//-----------------------------------------------------------------------------
15949
15950
//-----------------------------------------------------------------------------
15951
// Typical Docking call flow: (root level is generally public API):
15952
//-----------------------------------------------------------------------------
15953
// - NewFrame()                               new dear imgui frame
15954
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
15955
//    | - DockContextProcessUndockWindow()    - process one window undocking request
15956
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
15957
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
15958
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
15959
//    | - DockContextProcessDock()            - process one docking request
15960
//    | - DockNodeUpdate()
15961
//    |   - DockNodeUpdateForRootNode()
15962
//    |     - DockNodeUpdateFlagsAndCollapse()
15963
//    |     - DockNodeFindInfo()
15964
//    |   - destroy unused node or tab bar
15965
//    |   - create dock node host window
15966
//    |      - Begin() etc.
15967
//    |   - DockNodeStartMouseMovingWindow()
15968
//    |   - DockNodeTreeUpdatePosSize()
15969
//    |   - DockNodeTreeUpdateSplitter()
15970
//    |   - draw node background
15971
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
15972
//    |     - DockNodeAddTabBar()
15973
//    |     - DockNodeWindowMenuUpdate()
15974
//    |     - DockNodeCalcTabBarLayout()
15975
//    |     - BeginTabBarEx()
15976
//    |     - TabItemEx() calls
15977
//    |     - EndTabBar()
15978
//    |   - BeginDockableDragDropTarget()
15979
//    |      - DockNodeUpdate()               - recurse into child nodes...
15980
//-----------------------------------------------------------------------------
15981
// - DockSpace()                              user submit a dockspace into a window
15982
//    | Begin(Child)                          - create a child window
15983
//    | DockNodeUpdate()                      - call main dock node update function
15984
//    | End(Child)
15985
//    | ItemSize()
15986
//-----------------------------------------------------------------------------
15987
// - Begin()
15988
//    | BeginDocked()
15989
//    | BeginDockableDragDropSource()
15990
//    | BeginDockableDragDropTarget()
15991
//    | - DockNodePreviewDockRender()
15992
//-----------------------------------------------------------------------------
15993
// - EndFrame()
15994
//    | DockContextEndFrame()
15995
//-----------------------------------------------------------------------------
15996
15997
//-----------------------------------------------------------------------------
15998
// Docking: Internal Types
15999
//-----------------------------------------------------------------------------
16000
// - ImGuiDockRequestType
16001
// - ImGuiDockRequest
16002
// - ImGuiDockPreviewData
16003
// - ImGuiDockNodeSettings
16004
// - ImGuiDockContext
16005
//-----------------------------------------------------------------------------
16006
16007
enum ImGuiDockRequestType
16008
{
16009
    ImGuiDockRequestType_None = 0,
16010
    ImGuiDockRequestType_Dock,
16011
    ImGuiDockRequestType_Undock,
16012
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
16013
};
16014
16015
struct ImGuiDockRequest
16016
{
16017
    ImGuiDockRequestType    Type;
16018
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
16019
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
16020
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
16021
    ImGuiDir                DockSplitDir;
16022
    float                   DockSplitRatio;
16023
    bool                    DockSplitOuter;
16024
    ImGuiWindow*            UndockTargetWindow;
16025
    ImGuiDockNode*          UndockTargetNode;
16026
16027
    ImGuiDockRequest()
16028
0
    {
16029
0
        Type = ImGuiDockRequestType_None;
16030
0
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
16031
0
        DockTargetNode = UndockTargetNode = NULL;
16032
0
        DockSplitDir = ImGuiDir_None;
16033
0
        DockSplitRatio = 0.5f;
16034
0
        DockSplitOuter = false;
16035
0
    }
16036
};
16037
16038
struct ImGuiDockPreviewData
16039
{
16040
    ImGuiDockNode   FutureNode;
16041
    bool            IsDropAllowed;
16042
    bool            IsCenterAvailable;
16043
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
16044
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
16045
    ImGuiDockNode*  SplitNode;
16046
    ImGuiDir        SplitDir;
16047
    float           SplitRatio;
16048
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
16049
16050
0
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
16051
};
16052
16053
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
16054
struct ImGuiDockNodeSettings
16055
{
16056
    ImGuiID             ID;
16057
    ImGuiID             ParentNodeId;
16058
    ImGuiID             ParentWindowId;
16059
    ImGuiID             SelectedTabId;
16060
    signed char         SplitAxis;
16061
    char                Depth;
16062
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
16063
    ImVec2ih            Pos;
16064
    ImVec2ih            Size;
16065
    ImVec2ih            SizeRef;
16066
0
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
16067
};
16068
16069
//-----------------------------------------------------------------------------
16070
// Docking: Forward Declarations
16071
//-----------------------------------------------------------------------------
16072
16073
namespace ImGui
16074
{
16075
    // ImGuiDockContext
16076
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
16077
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
16078
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
16079
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
16080
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
16081
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
16082
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
16083
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
16084
16085
    // ImGuiDockNode
16086
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
16087
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
16088
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
16089
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
16090
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
16091
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
16092
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
16093
    static void             DockNodeUpdate(ImGuiDockNode* node);
16094
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
16095
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
16096
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
16097
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
16098
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
16099
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
16100
    static void             DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
16101
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
16102
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
16103
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
16104
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
16105
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
16106
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
16107
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
16108
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
16109
0
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
16110
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
16111
16112
    // ImGuiDockNode tree manipulations
16113
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
16114
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
16115
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
16116
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
16117
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
16118
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
16119
16120
    // Settings
16121
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
16122
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
16123
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
16124
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
16125
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
16126
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
16127
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
16128
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
16129
}
16130
16131
//-----------------------------------------------------------------------------
16132
// Docking: ImGuiDockContext
16133
//-----------------------------------------------------------------------------
16134
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
16135
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
16136
// At boot time only, we run a simple GC to remove nodes that have no references.
16137
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
16138
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
16139
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
16140
//-----------------------------------------------------------------------------
16141
// - DockContextInitialize()
16142
// - DockContextShutdown()
16143
// - DockContextClearNodes()
16144
// - DockContextRebuildNodes()
16145
// - DockContextNewFrameUpdateUndocking()
16146
// - DockContextNewFrameUpdateDocking()
16147
// - DockContextEndFrame()
16148
// - DockContextFindNodeByID()
16149
// - DockContextBindNodeToWindow()
16150
// - DockContextGenNodeID()
16151
// - DockContextAddNode()
16152
// - DockContextRemoveNode()
16153
// - ImGuiDockContextPruneNodeData
16154
// - DockContextPruneUnusedSettingsNodes()
16155
// - DockContextBuildNodesFromSettings()
16156
// - DockContextBuildAddWindowsToNodes()
16157
//-----------------------------------------------------------------------------
16158
16159
void ImGui::DockContextInitialize(ImGuiContext* ctx)
16160
1
{
16161
1
    ImGuiContext& g = *ctx;
16162
16163
    // Add .ini handle for persistent docking data
16164
1
    ImGuiSettingsHandler ini_handler;
16165
1
    ini_handler.TypeName = "Docking";
16166
1
    ini_handler.TypeHash = ImHashStr("Docking");
16167
1
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
16168
1
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
16169
1
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
16170
1
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
16171
1
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
16172
1
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
16173
1
    g.SettingsHandlers.push_back(ini_handler);
16174
16175
1
    g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
16176
1
}
16177
16178
void ImGui::DockContextShutdown(ImGuiContext* ctx)
16179
0
{
16180
0
    ImGuiDockContext* dc = &ctx->DockContext;
16181
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
16182
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16183
0
            IM_DELETE(node);
16184
0
}
16185
16186
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
16187
0
{
16188
0
    IM_UNUSED(ctx);
16189
0
    IM_ASSERT(ctx == GImGui);
16190
0
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
16191
0
    DockBuilderRemoveNodeChildNodes(root_id);
16192
0
}
16193
16194
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
16195
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
16196
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
16197
0
{
16198
0
    ImGuiContext& g = *ctx;
16199
0
    ImGuiDockContext* dc = &ctx->DockContext;
16200
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
16201
0
    SaveIniSettingsToMemory();
16202
0
    ImGuiID root_id = 0; // Rebuild all
16203
0
    DockContextClearNodes(ctx, root_id, false);
16204
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
16205
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
16206
0
}
16207
16208
// Docking context update function, called by NewFrame()
16209
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
16210
58.4k
{
16211
58.4k
    ImGuiContext& g = *ctx;
16212
58.4k
    ImGuiDockContext* dc = &ctx->DockContext;
16213
58.4k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
16214
0
    {
16215
0
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
16216
0
            DockContextClearNodes(ctx, 0, true);
16217
0
        return;
16218
0
    }
16219
16220
    // Setting NoSplit at runtime merges all nodes
16221
58.4k
    if (g.IO.ConfigDockingNoSplit)
16222
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
16223
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16224
0
                if (node->IsRootNode() && node->IsSplitNode())
16225
0
                {
16226
0
                    DockBuilderRemoveNodeChildNodes(node->ID);
16227
                    //dc->WantFullRebuild = true;
16228
0
                }
16229
16230
    // Process full rebuild
16231
#if 0
16232
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
16233
        dc->WantFullRebuild = true;
16234
#endif
16235
58.4k
    if (dc->WantFullRebuild)
16236
0
    {
16237
0
        DockContextRebuildNodes(ctx);
16238
0
        dc->WantFullRebuild = false;
16239
0
    }
16240
16241
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
16242
58.4k
    for (ImGuiDockRequest& req : dc->Requests)
16243
0
    {
16244
0
        if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetWindow)
16245
0
            DockContextProcessUndockWindow(ctx, req.UndockTargetWindow);
16246
0
        else if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetNode)
16247
0
            DockContextProcessUndockNode(ctx, req.UndockTargetNode);
16248
0
    }
16249
58.4k
}
16250
16251
// Docking context update function, called by NewFrame()
16252
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
16253
58.4k
{
16254
58.4k
    ImGuiContext& g = *ctx;
16255
58.4k
    ImGuiDockContext* dc = &ctx->DockContext;
16256
58.4k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
16257
0
        return;
16258
16259
    // [DEBUG] Store hovered dock node.
16260
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
16261
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
16262
58.4k
    g.DebugHoveredDockNode = NULL;
16263
58.4k
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
16264
12
    {
16265
12
        if (hovered_window->DockNodeAsHost)
16266
0
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
16267
12
        else if (hovered_window->RootWindow->DockNode)
16268
0
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
16269
12
    }
16270
16271
    // Process Docking requests
16272
58.4k
    for (ImGuiDockRequest& req : dc->Requests)
16273
0
        if (req.Type == ImGuiDockRequestType_Dock)
16274
0
            DockContextProcessDock(ctx, &req);
16275
58.4k
    dc->Requests.resize(0);
16276
16277
    // Create windows for each automatic docking nodes
16278
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
16279
58.4k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
16280
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16281
0
            if (node->IsFloatingNode())
16282
0
                DockNodeUpdate(node);
16283
58.4k
}
16284
16285
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
16286
58.4k
{
16287
    // Draw backgrounds of node missing their window
16288
58.4k
    ImGuiContext& g = *ctx;
16289
58.4k
    ImGuiDockContext* dc = &g.DockContext;
16290
58.4k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
16291
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16292
0
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
16293
0
            {
16294
0
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
16295
0
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), g.Style.DockingSeparatorSize);
16296
0
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16297
0
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
16298
0
            }
16299
58.4k
}
16300
16301
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
16302
0
{
16303
0
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
16304
0
}
16305
16306
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
16307
0
{
16308
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
16309
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
16310
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
16311
0
    ImGuiID id = 0x0001;
16312
0
    while (DockContextFindNodeByID(ctx, id) != NULL)
16313
0
        id++;
16314
0
    return id;
16315
0
}
16316
16317
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
16318
0
{
16319
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
16320
0
    ImGuiContext& g = *ctx;
16321
0
    if (id == 0)
16322
0
        id = DockContextGenNodeID(ctx);
16323
0
    else
16324
0
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
16325
16326
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
16327
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
16328
0
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
16329
0
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
16330
0
    return node;
16331
0
}
16332
16333
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
16334
0
{
16335
0
    ImGuiContext& g = *ctx;
16336
0
    ImGuiDockContext* dc = &ctx->DockContext;
16337
16338
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
16339
0
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
16340
0
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
16341
0
    IM_ASSERT(node->Windows.Size == 0);
16342
16343
0
    if (node->HostWindow)
16344
0
        node->HostWindow->DockNodeAsHost = NULL;
16345
16346
0
    ImGuiDockNode* parent_node = node->ParentNode;
16347
0
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
16348
0
    if (merge)
16349
0
    {
16350
0
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
16351
0
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
16352
0
        DockNodeTreeMerge(&g, parent_node, sibling_node);
16353
0
    }
16354
0
    else
16355
0
    {
16356
0
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
16357
0
            if (parent_node->ChildNodes[n] == node)
16358
0
                node->ParentNode->ChildNodes[n] = NULL;
16359
0
        dc->Nodes.SetVoidPtr(node->ID, NULL);
16360
0
        IM_DELETE(node);
16361
0
    }
16362
0
}
16363
16364
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
16365
0
{
16366
0
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
16367
0
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
16368
0
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
16369
0
}
16370
16371
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
16372
struct ImGuiDockContextPruneNodeData
16373
{
16374
    int         CountWindows, CountChildWindows, CountChildNodes;
16375
    ImGuiID     RootId;
16376
0
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
16377
};
16378
16379
// Garbage collect unused nodes (run once at init time)
16380
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
16381
0
{
16382
0
    ImGuiContext& g = *ctx;
16383
0
    ImGuiDockContext* dc = &ctx->DockContext;
16384
0
    IM_ASSERT(g.Windows.Size == 0);
16385
16386
0
    ImPool<ImGuiDockContextPruneNodeData> pool;
16387
0
    pool.Reserve(dc->NodesSettings.Size);
16388
16389
    // Count child nodes and compute RootID
16390
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16391
0
    {
16392
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16393
0
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
16394
0
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
16395
0
        if (settings->ParentNodeId)
16396
0
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
16397
0
    }
16398
16399
    // Count reference to dock ids from dockspaces
16400
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
16401
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16402
0
    {
16403
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16404
0
        if (settings->ParentWindowId != 0)
16405
0
            if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
16406
0
                if (window_settings->DockId)
16407
0
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
16408
0
                        data->CountChildNodes++;
16409
0
    }
16410
16411
    // Count reference to dock ids from window settings
16412
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
16413
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
16414
0
        if (ImGuiID dock_id = settings->DockId)
16415
0
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
16416
0
            {
16417
0
                data->CountWindows++;
16418
0
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
16419
0
                    data_root->CountChildWindows++;
16420
0
            }
16421
16422
    // Prune
16423
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16424
0
    {
16425
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16426
0
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
16427
0
        if (data->CountWindows > 1)
16428
0
            continue;
16429
0
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
16430
16431
0
        bool remove = false;
16432
0
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
16433
0
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
16434
0
        remove |= (data_root->CountChildWindows == 0);
16435
0
        if (remove)
16436
0
        {
16437
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
16438
0
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
16439
0
            settings->ID = 0;
16440
0
        }
16441
0
    }
16442
0
}
16443
16444
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
16445
0
{
16446
    // Build nodes
16447
0
    for (int node_n = 0; node_n < node_settings_count; node_n++)
16448
0
    {
16449
0
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
16450
0
        if (settings->ID == 0)
16451
0
            continue;
16452
0
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
16453
0
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
16454
0
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
16455
0
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
16456
0
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
16457
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
16458
0
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
16459
0
            node->ParentNode->ChildNodes[0] = node;
16460
0
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
16461
0
            node->ParentNode->ChildNodes[1] = node;
16462
0
        node->SelectedTabId = settings->SelectedTabId;
16463
0
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
16464
0
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
16465
16466
        // Bind host window immediately if it already exist (in case of a rebuild)
16467
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
16468
0
        char host_window_title[20];
16469
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16470
0
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
16471
0
    }
16472
0
}
16473
16474
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
16475
0
{
16476
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
16477
0
    ImGuiContext& g = *ctx;
16478
0
    for (ImGuiWindow* window : g.Windows)
16479
0
    {
16480
0
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
16481
0
            continue;
16482
0
        if (window->DockNode != NULL)
16483
0
            continue;
16484
16485
0
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
16486
0
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
16487
0
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
16488
0
            DockNodeAddWindow(node, window, true);
16489
0
    }
16490
0
}
16491
16492
//-----------------------------------------------------------------------------
16493
// Docking: ImGuiDockContext Docking/Undocking functions
16494
//-----------------------------------------------------------------------------
16495
// - DockContextQueueDock()
16496
// - DockContextQueueUndockWindow()
16497
// - DockContextQueueUndockNode()
16498
// - DockContextQueueNotifyRemovedNode()
16499
// - DockContextProcessDock()
16500
// - DockContextProcessUndockWindow()
16501
// - DockContextProcessUndockNode()
16502
// - DockContextCalcDropPosForDocking()
16503
//-----------------------------------------------------------------------------
16504
16505
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
16506
0
{
16507
0
    IM_ASSERT(target != payload);
16508
0
    ImGuiDockRequest req;
16509
0
    req.Type = ImGuiDockRequestType_Dock;
16510
0
    req.DockTargetWindow = target;
16511
0
    req.DockTargetNode = target_node;
16512
0
    req.DockPayload = payload;
16513
0
    req.DockSplitDir = split_dir;
16514
0
    req.DockSplitRatio = split_ratio;
16515
0
    req.DockSplitOuter = split_outer;
16516
0
    ctx->DockContext.Requests.push_back(req);
16517
0
}
16518
16519
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
16520
0
{
16521
0
    ImGuiDockRequest req;
16522
0
    req.Type = ImGuiDockRequestType_Undock;
16523
0
    req.UndockTargetWindow = window;
16524
0
    ctx->DockContext.Requests.push_back(req);
16525
0
}
16526
16527
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
16528
0
{
16529
0
    ImGuiDockRequest req;
16530
0
    req.Type = ImGuiDockRequestType_Undock;
16531
0
    req.UndockTargetNode = node;
16532
0
    ctx->DockContext.Requests.push_back(req);
16533
0
}
16534
16535
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
16536
0
{
16537
0
    ImGuiDockContext* dc = &ctx->DockContext;
16538
0
    for (ImGuiDockRequest& req : dc->Requests)
16539
0
        if (req.DockTargetNode == node)
16540
0
            req.Type = ImGuiDockRequestType_None;
16541
0
}
16542
16543
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
16544
0
{
16545
0
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
16546
0
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
16547
16548
0
    ImGuiContext& g = *ctx;
16549
0
    IM_UNUSED(g);
16550
16551
0
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
16552
0
    ImGuiWindow* target_window = req->DockTargetWindow;
16553
0
    ImGuiDockNode* node = req->DockTargetNode;
16554
0
    if (payload_window)
16555
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
16556
0
    else
16557
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
16558
16559
    // Decide which Tab will be selected at the end of the operation
16560
0
    ImGuiID next_selected_id = 0;
16561
0
    ImGuiDockNode* payload_node = NULL;
16562
0
    if (payload_window)
16563
0
    {
16564
0
        payload_node = payload_window->DockNodeAsHost;
16565
0
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
16566
0
        if (payload_node && payload_node->IsLeafNode())
16567
0
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
16568
0
        if (payload_node == NULL)
16569
0
            next_selected_id = payload_window->TabId;
16570
0
    }
16571
16572
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
16573
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
16574
0
    if (node)
16575
0
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
16576
0
    if (node && target_window && node == target_window->DockNodeAsHost)
16577
0
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
16578
16579
    // Create new node and add existing window to it
16580
0
    if (node == NULL)
16581
0
    {
16582
0
        node = DockContextAddNode(ctx, 0);
16583
0
        node->Pos = target_window->Pos;
16584
0
        node->Size = target_window->Size;
16585
0
        if (target_window->DockNodeAsHost == NULL)
16586
0
        {
16587
0
            DockNodeAddWindow(node, target_window, true);
16588
0
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
16589
0
            target_window->DockIsActive = true;
16590
0
        }
16591
0
    }
16592
16593
0
    ImGuiDir split_dir = req->DockSplitDir;
16594
0
    if (split_dir != ImGuiDir_None)
16595
0
    {
16596
        // Split into two, one side will be our payload node unless we are dropping a loose window
16597
0
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16598
0
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
16599
0
        const float split_ratio = req->DockSplitRatio;
16600
0
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
16601
0
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
16602
0
        new_node->HostWindow = node->HostWindow;
16603
0
        node = new_node;
16604
0
    }
16605
0
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16606
16607
0
    if (node != payload_node)
16608
0
    {
16609
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
16610
0
        if (node->Windows.Size > 0 && node->TabBar == NULL)
16611
0
        {
16612
0
            DockNodeAddTabBar(node);
16613
0
            for (int n = 0; n < node->Windows.Size; n++)
16614
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16615
0
        }
16616
16617
0
        if (payload_node != NULL)
16618
0
        {
16619
            // Transfer full payload node (with 1+ child windows or child nodes)
16620
0
            if (payload_node->IsSplitNode())
16621
0
            {
16622
0
                if (node->Windows.Size > 0)
16623
0
                {
16624
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
16625
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
16626
                    // This allows us to preserve some of the underlying dock tree settings nicely.
16627
0
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
16628
0
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
16629
0
                    if (visible_node->TabBar)
16630
0
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
16631
0
                    DockNodeMoveWindows(node, visible_node);
16632
0
                    DockNodeMoveWindows(visible_node, node);
16633
0
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
16634
0
                }
16635
0
                if (node->IsCentralNode())
16636
0
                {
16637
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
16638
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
16639
0
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
16640
0
                    IM_ASSERT(last_focused_node != NULL);
16641
0
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
16642
0
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
16643
0
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
16644
0
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
16645
0
                    last_focused_root_node->CentralNode = last_focused_node;
16646
0
                }
16647
16648
0
                IM_ASSERT(node->Windows.Size == 0);
16649
0
                DockNodeMoveChildNodes(node, payload_node);
16650
0
            }
16651
0
            else
16652
0
            {
16653
0
                const ImGuiID payload_dock_id = payload_node->ID;
16654
0
                DockNodeMoveWindows(node, payload_node);
16655
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
16656
0
            }
16657
0
            DockContextRemoveNode(ctx, payload_node, true);
16658
0
        }
16659
0
        else if (payload_window)
16660
0
        {
16661
            // Transfer single window
16662
0
            const ImGuiID payload_dock_id = payload_window->DockId;
16663
0
            node->VisibleWindow = payload_window;
16664
0
            DockNodeAddWindow(node, payload_window, true);
16665
0
            if (payload_dock_id != 0)
16666
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
16667
0
        }
16668
0
    }
16669
0
    else
16670
0
    {
16671
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
16672
0
        node->WantHiddenTabBarUpdate = true;
16673
0
    }
16674
16675
    // Update selection immediately
16676
0
    if (ImGuiTabBar* tab_bar = node->TabBar)
16677
0
        tab_bar->NextSelectedTabId = next_selected_id;
16678
0
    MarkIniSettingsDirty();
16679
0
}
16680
16681
// Problem:
16682
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
16683
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
16684
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
16685
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
16686
// Solution:
16687
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
16688
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
16689
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
16690
0
{
16691
0
    if (ref_viewport == NULL)
16692
0
        return size;
16693
16694
0
    ImGuiContext& g = *GImGui;
16695
0
    ImVec2 max_size = ImTrunc(ref_viewport->WorkSize * 0.90f);
16696
0
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
16697
0
    {
16698
0
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
16699
0
        max_size = ImTrunc(monitor->WorkSize * 0.90f);
16700
0
    }
16701
0
    return ImMin(size, max_size);
16702
0
}
16703
16704
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
16705
0
{
16706
0
    ImGuiContext& g = *ctx;
16707
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
16708
0
    if (window->DockNode)
16709
0
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
16710
0
    else
16711
0
        window->DockId = 0;
16712
0
    window->Collapsed = false;
16713
0
    window->DockIsActive = false;
16714
0
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
16715
0
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
16716
16717
0
    MarkIniSettingsDirty();
16718
0
}
16719
16720
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
16721
0
{
16722
0
    ImGuiContext& g = *ctx;
16723
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
16724
0
    IM_ASSERT(node->IsLeafNode());
16725
0
    IM_ASSERT(node->Windows.Size >= 1);
16726
16727
0
    if (node->IsRootNode() || node->IsCentralNode())
16728
0
    {
16729
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
16730
0
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
16731
0
        new_node->Pos = node->Pos;
16732
0
        new_node->Size = node->Size;
16733
0
        new_node->SizeRef = node->SizeRef;
16734
0
        DockNodeMoveWindows(new_node, node);
16735
0
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
16736
0
        node = new_node;
16737
0
    }
16738
0
    else
16739
0
    {
16740
        // Otherwise extract our node and merge our sibling back into the parent node.
16741
0
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
16742
0
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
16743
0
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
16744
0
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
16745
0
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
16746
0
        node->ParentNode = NULL;
16747
0
    }
16748
0
    for (ImGuiWindow* window : node->Windows)
16749
0
    {
16750
0
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16751
0
        if (window->ParentWindow)
16752
0
            window->ParentWindow->DC.ChildWindows.find_erase(window);
16753
0
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
16754
0
    }
16755
0
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
16756
0
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
16757
0
    node->WantMouseMove = true;
16758
0
    MarkIniSettingsDirty();
16759
0
}
16760
16761
// This is mostly used for automation.
16762
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
16763
0
{
16764
0
    if (target != NULL && target_node == NULL)
16765
0
        target_node = target->DockNode;
16766
16767
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
16768
    // (which would be functionally identical) we only show the outer one. Reflect this here.
16769
0
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
16770
0
        split_outer = true;
16771
0
    ImGuiDockPreviewData split_data;
16772
0
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
16773
0
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
16774
0
        return false;
16775
0
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
16776
0
    return true;
16777
0
}
16778
16779
//-----------------------------------------------------------------------------
16780
// Docking: ImGuiDockNode
16781
//-----------------------------------------------------------------------------
16782
// - DockNodeGetTabOrder()
16783
// - DockNodeAddWindow()
16784
// - DockNodeRemoveWindow()
16785
// - DockNodeMoveChildNodes()
16786
// - DockNodeMoveWindows()
16787
// - DockNodeApplyPosSizeToWindows()
16788
// - DockNodeHideHostWindow()
16789
// - ImGuiDockNodeFindInfoResults
16790
// - DockNodeFindInfo()
16791
// - DockNodeFindWindowByID()
16792
// - DockNodeUpdateFlagsAndCollapse()
16793
// - DockNodeUpdateHasCentralNodeFlag()
16794
// - DockNodeUpdateVisibleFlag()
16795
// - DockNodeStartMouseMovingWindow()
16796
// - DockNodeUpdate()
16797
// - DockNodeUpdateWindowMenu()
16798
// - DockNodeBeginAmendTabBar()
16799
// - DockNodeEndAmendTabBar()
16800
// - DockNodeUpdateTabBar()
16801
// - DockNodeAddTabBar()
16802
// - DockNodeRemoveTabBar()
16803
// - DockNodeIsDropAllowedOne()
16804
// - DockNodeIsDropAllowed()
16805
// - DockNodeCalcTabBarLayout()
16806
// - DockNodeCalcSplitRects()
16807
// - DockNodeCalcDropRectsAndTestMousePos()
16808
// - DockNodePreviewDockSetup()
16809
// - DockNodePreviewDockRender()
16810
//-----------------------------------------------------------------------------
16811
16812
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
16813
0
{
16814
0
    ID = id;
16815
0
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
16816
0
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
16817
0
    TabBar = NULL;
16818
0
    SplitAxis = ImGuiAxis_None;
16819
16820
0
    State = ImGuiDockNodeState_Unknown;
16821
0
    LastBgColor = IM_COL32_WHITE;
16822
0
    HostWindow = VisibleWindow = NULL;
16823
0
    CentralNode = OnlyNodeWithWindows = NULL;
16824
0
    CountNodeWithWindows = 0;
16825
0
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
16826
0
    LastFocusedNodeId = 0;
16827
0
    SelectedTabId = 0;
16828
0
    WantCloseTabId = 0;
16829
0
    RefViewportId = 0;
16830
0
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
16831
0
    AuthorityForViewport = ImGuiDataAuthority_Auto;
16832
0
    IsVisible = true;
16833
0
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
16834
0
    IsBgDrawnThisFrame = false;
16835
0
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
16836
0
}
16837
16838
ImGuiDockNode::~ImGuiDockNode()
16839
0
{
16840
0
    IM_DELETE(TabBar);
16841
0
    TabBar = NULL;
16842
0
    ChildNodes[0] = ChildNodes[1] = NULL;
16843
0
}
16844
16845
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
16846
0
{
16847
0
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
16848
0
    if (tab_bar == NULL)
16849
0
        return -1;
16850
0
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
16851
0
    return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
16852
0
}
16853
16854
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
16855
0
{
16856
0
    window->Hidden = true;
16857
0
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
16858
0
}
16859
16860
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
16861
0
{
16862
0
    ImGuiContext& g = *GImGui; (void)g;
16863
0
    if (window->DockNode)
16864
0
    {
16865
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
16866
0
        IM_ASSERT(window->DockNode->ID != node->ID);
16867
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
16868
0
    }
16869
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
16870
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16871
16872
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
16873
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
16874
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
16875
0
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
16876
0
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
16877
16878
0
    node->Windows.push_back(window);
16879
0
    node->WantHiddenTabBarUpdate = true;
16880
0
    window->DockNode = node;
16881
0
    window->DockId = node->ID;
16882
0
    window->DockIsActive = (node->Windows.Size > 1);
16883
0
    window->DockTabWantClose = false;
16884
16885
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
16886
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
16887
0
    if (node->HostWindow == NULL && node->IsFloatingNode())
16888
0
    {
16889
0
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
16890
0
            node->AuthorityForPos = ImGuiDataAuthority_Window;
16891
0
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
16892
0
            node->AuthorityForSize = ImGuiDataAuthority_Window;
16893
0
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
16894
0
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
16895
0
    }
16896
16897
    // Add to tab bar if requested
16898
0
    if (add_to_tab_bar)
16899
0
    {
16900
0
        if (node->TabBar == NULL)
16901
0
        {
16902
0
            DockNodeAddTabBar(node);
16903
0
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
16904
16905
            // Add existing windows
16906
0
            for (int n = 0; n < node->Windows.Size - 1; n++)
16907
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16908
0
        }
16909
0
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
16910
0
    }
16911
16912
0
    DockNodeUpdateVisibleFlag(node);
16913
16914
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
16915
0
    if (node->HostWindow)
16916
0
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
16917
0
}
16918
16919
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
16920
0
{
16921
0
    ImGuiContext& g = *GImGui;
16922
0
    IM_ASSERT(window->DockNode == node);
16923
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
16924
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
16925
0
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
16926
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16927
16928
0
    window->DockNode = NULL;
16929
0
    window->DockIsActive = window->DockTabWantClose = false;
16930
0
    window->DockId = save_dock_id;
16931
0
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16932
0
    if (window->ParentWindow)
16933
0
        window->ParentWindow->DC.ChildWindows.find_erase(window);
16934
0
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
16935
16936
0
    if (node->HostWindow && node->HostWindow->ViewportOwned)
16937
0
    {
16938
        // When undocking from a user interaction this will always run in NewFrame() and have not much effect.
16939
        // But mid-frame, if we clear viewport we need to mark window as hidden as well.
16940
0
        window->Viewport = NULL;
16941
0
        window->ViewportId = 0;
16942
0
        window->ViewportOwned = false;
16943
0
        window->Hidden = true;
16944
0
    }
16945
16946
    // Remove window
16947
0
    bool erased = false;
16948
0
    for (int n = 0; n < node->Windows.Size; n++)
16949
0
        if (node->Windows[n] == window)
16950
0
        {
16951
0
            node->Windows.erase(node->Windows.Data + n);
16952
0
            erased = true;
16953
0
            break;
16954
0
        }
16955
0
    if (!erased)
16956
0
        IM_ASSERT(erased);
16957
0
    if (node->VisibleWindow == window)
16958
0
        node->VisibleWindow = NULL;
16959
16960
    // Remove tab and possibly tab bar
16961
0
    node->WantHiddenTabBarUpdate = true;
16962
0
    if (node->TabBar)
16963
0
    {
16964
0
        TabBarRemoveTab(node->TabBar, window->TabId);
16965
0
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
16966
0
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
16967
0
            DockNodeRemoveTabBar(node);
16968
0
    }
16969
16970
0
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
16971
0
    {
16972
        // Automatic dock node delete themselves if they are not holding at least one tab
16973
0
        DockContextRemoveNode(&g, node, true);
16974
0
        return;
16975
0
    }
16976
16977
0
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
16978
0
    {
16979
0
        ImGuiWindow* remaining_window = node->Windows[0];
16980
        // Note: we used to transport viewport ownership here.
16981
0
        remaining_window->Collapsed = node->HostWindow->Collapsed;
16982
0
    }
16983
16984
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
16985
0
    DockNodeUpdateVisibleFlag(node);
16986
0
}
16987
16988
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16989
0
{
16990
0
    IM_ASSERT(dst_node->Windows.Size == 0);
16991
0
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
16992
0
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
16993
0
    if (dst_node->ChildNodes[0])
16994
0
        dst_node->ChildNodes[0]->ParentNode = dst_node;
16995
0
    if (dst_node->ChildNodes[1])
16996
0
        dst_node->ChildNodes[1]->ParentNode = dst_node;
16997
0
    dst_node->SplitAxis = src_node->SplitAxis;
16998
0
    dst_node->SizeRef = src_node->SizeRef;
16999
0
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
17000
0
}
17001
17002
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
17003
0
{
17004
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
17005
0
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
17006
0
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
17007
0
    if (src_tab_bar != NULL)
17008
0
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
17009
17010
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
17011
0
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
17012
0
    if (move_tab_bar)
17013
0
    {
17014
0
        dst_node->TabBar = src_node->TabBar;
17015
0
        src_node->TabBar = NULL;
17016
0
    }
17017
17018
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
17019
0
    for (ImGuiWindow* window : src_node->Windows)
17020
0
    {
17021
0
        window->DockNode = NULL;
17022
0
        window->DockIsActive = false;
17023
0
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
17024
0
    }
17025
0
    src_node->Windows.clear();
17026
17027
0
    if (!move_tab_bar && src_node->TabBar)
17028
0
    {
17029
0
        if (dst_node->TabBar)
17030
0
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
17031
0
        DockNodeRemoveTabBar(src_node);
17032
0
    }
17033
0
}
17034
17035
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
17036
0
{
17037
0
    for (ImGuiWindow* window : node->Windows)
17038
0
    {
17039
0
        SetWindowPos(window, node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
17040
0
        SetWindowSize(window, node->Size, ImGuiCond_Always);
17041
0
    }
17042
0
}
17043
17044
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
17045
0
{
17046
0
    if (node->HostWindow)
17047
0
    {
17048
0
        if (node->HostWindow->DockNodeAsHost == node)
17049
0
            node->HostWindow->DockNodeAsHost = NULL;
17050
0
        node->HostWindow = NULL;
17051
0
    }
17052
17053
0
    if (node->Windows.Size == 1)
17054
0
    {
17055
0
        node->VisibleWindow = node->Windows[0];
17056
0
        node->Windows[0]->DockIsActive = false;
17057
0
    }
17058
17059
0
    if (node->TabBar)
17060
0
        DockNodeRemoveTabBar(node);
17061
0
}
17062
17063
// Search function called once by root node in DockNodeUpdate()
17064
struct ImGuiDockNodeTreeInfo
17065
{
17066
    ImGuiDockNode*      CentralNode;
17067
    ImGuiDockNode*      FirstNodeWithWindows;
17068
    int                 CountNodesWithWindows;
17069
    //ImGuiWindowClass  WindowClassForMerges;
17070
17071
0
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
17072
};
17073
17074
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
17075
0
{
17076
0
    if (node->Windows.Size > 0)
17077
0
    {
17078
0
        if (info->FirstNodeWithWindows == NULL)
17079
0
            info->FirstNodeWithWindows = node;
17080
0
        info->CountNodesWithWindows++;
17081
0
    }
17082
0
    if (node->IsCentralNode())
17083
0
    {
17084
0
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
17085
0
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
17086
0
        info->CentralNode = node;
17087
0
    }
17088
0
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
17089
0
        return;
17090
0
    if (node->ChildNodes[0])
17091
0
        DockNodeFindInfo(node->ChildNodes[0], info);
17092
0
    if (node->ChildNodes[1])
17093
0
        DockNodeFindInfo(node->ChildNodes[1], info);
17094
0
}
17095
17096
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
17097
0
{
17098
0
    IM_ASSERT(id != 0);
17099
0
    for (ImGuiWindow* window : node->Windows)
17100
0
        if (window->ID == id)
17101
0
            return window;
17102
0
    return NULL;
17103
0
}
17104
17105
// - Remove inactive windows/nodes.
17106
// - Update visibility flag.
17107
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
17108
0
{
17109
0
    ImGuiContext& g = *GImGui;
17110
0
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
17111
17112
    // Inherit most flags
17113
0
    if (node->ParentNode)
17114
0
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17115
17116
    // Recurse into children
17117
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
17118
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
17119
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
17120
0
    node->HasCentralNodeChild = false;
17121
0
    if (node->ChildNodes[0])
17122
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
17123
0
    if (node->ChildNodes[1])
17124
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
17125
17126
    // Remove inactive windows, collapse nodes
17127
    // Merge node flags overrides stored in windows
17128
0
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
17129
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17130
0
    {
17131
0
        ImGuiWindow* window = node->Windows[window_n];
17132
0
        IM_ASSERT(window->DockNode == node);
17133
17134
0
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
17135
0
        bool remove = false;
17136
0
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
17137
0
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
17138
0
        remove |= (window->DockTabWantClose);
17139
0
        if (remove)
17140
0
        {
17141
0
            window->DockTabWantClose = false;
17142
0
            if (node->Windows.Size == 1 && !node->IsCentralNode())
17143
0
            {
17144
0
                DockNodeHideHostWindow(node);
17145
0
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
17146
0
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
17147
0
                return;
17148
0
            }
17149
0
            DockNodeRemoveWindow(node, window, node->ID);
17150
0
            window_n--;
17151
0
            continue;
17152
0
        }
17153
17154
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
17155
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
17156
0
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
17157
0
    }
17158
0
    node->UpdateMergedFlags();
17159
17160
    // Auto-hide tab bar option
17161
0
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
17162
0
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
17163
0
        node->WantHiddenTabBarToggle = true;
17164
0
    node->WantHiddenTabBarUpdate = false;
17165
17166
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
17167
0
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
17168
0
        node->WantHiddenTabBarToggle = false;
17169
17170
    // Apply toggles at a single point of the frame (here!)
17171
0
    if (node->Windows.Size > 1)
17172
0
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
17173
0
    else if (node->WantHiddenTabBarToggle)
17174
0
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
17175
0
    node->WantHiddenTabBarToggle = false;
17176
17177
0
    DockNodeUpdateVisibleFlag(node);
17178
0
}
17179
17180
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
17181
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
17182
0
{
17183
0
    node->HasCentralNodeChild = false;
17184
0
    if (node->ChildNodes[0])
17185
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
17186
0
    if (node->ChildNodes[1])
17187
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
17188
0
    if (node->IsRootNode())
17189
0
    {
17190
0
        ImGuiDockNode* mark_node = node->CentralNode;
17191
0
        while (mark_node)
17192
0
        {
17193
0
            mark_node->HasCentralNodeChild = true;
17194
0
            mark_node = mark_node->ParentNode;
17195
0
        }
17196
0
    }
17197
0
}
17198
17199
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
17200
0
{
17201
    // Update visibility flag
17202
0
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
17203
0
    is_visible |= (node->Windows.Size > 0);
17204
0
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
17205
0
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
17206
0
    node->IsVisible = is_visible;
17207
0
}
17208
17209
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
17210
0
{
17211
0
    ImGuiContext& g = *GImGui;
17212
0
    IM_ASSERT(node->WantMouseMove == true);
17213
0
    StartMouseMovingWindow(window);
17214
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
17215
0
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
17216
0
    node->WantMouseMove = false;
17217
0
}
17218
17219
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
17220
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
17221
0
{
17222
0
    DockNodeUpdateFlagsAndCollapse(node);
17223
17224
    // - Setup central node pointers
17225
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
17226
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
17227
0
    ImGuiDockNodeTreeInfo info;
17228
0
    DockNodeFindInfo(node, &info);
17229
0
    node->CentralNode = info.CentralNode;
17230
0
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
17231
0
    node->CountNodeWithWindows = info.CountNodesWithWindows;
17232
0
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
17233
0
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
17234
17235
    // Copy the window class from of our first window so it can be used for proper dock filtering.
17236
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
17237
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
17238
0
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
17239
0
    {
17240
0
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
17241
0
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
17242
0
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
17243
0
            {
17244
0
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
17245
0
                break;
17246
0
            }
17247
0
    }
17248
17249
0
    ImGuiDockNode* mark_node = node->CentralNode;
17250
0
    while (mark_node)
17251
0
    {
17252
0
        mark_node->HasCentralNodeChild = true;
17253
0
        mark_node = mark_node->ParentNode;
17254
0
    }
17255
0
}
17256
17257
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
17258
0
{
17259
    // Remove ourselves from any previous different host window
17260
    // This can happen if a user mistakenly does (see #4295 for details):
17261
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
17262
    //  - N+1: NewFrame()                   // will create floating host window for that node
17263
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
17264
0
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
17265
0
        node->HostWindow->DockNodeAsHost = NULL;
17266
17267
0
    host_window->DockNodeAsHost = node;
17268
0
    node->HostWindow = host_window;
17269
0
}
17270
17271
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
17272
0
{
17273
0
    ImGuiContext& g = *GImGui;
17274
0
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
17275
0
    node->LastFrameAlive = g.FrameCount;
17276
0
    node->IsBgDrawnThisFrame = false;
17277
17278
0
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
17279
0
    if (node->IsRootNode())
17280
0
        DockNodeUpdateForRootNode(node);
17281
17282
    // Remove tab bar if not needed
17283
0
    if (node->TabBar && node->IsNoTabBar())
17284
0
        DockNodeRemoveTabBar(node);
17285
17286
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
17287
0
    bool want_to_hide_host_window = false;
17288
0
    if (node->IsFloatingNode())
17289
0
    {
17290
0
        if (node->Windows.Size <= 1 && node->IsLeafNode())
17291
0
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
17292
0
                want_to_hide_host_window = true;
17293
0
        if (node->CountNodeWithWindows == 0)
17294
0
            want_to_hide_host_window = true;
17295
0
    }
17296
0
    if (want_to_hide_host_window)
17297
0
    {
17298
0
        if (node->Windows.Size == 1)
17299
0
        {
17300
            // Floating window pos/size is authoritative
17301
0
            ImGuiWindow* single_window = node->Windows[0];
17302
0
            node->Pos = single_window->Pos;
17303
0
            node->Size = single_window->SizeFull;
17304
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
17305
17306
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
17307
0
            if (node->HostWindow && g.NavWindow == node->HostWindow)
17308
0
                FocusWindow(single_window);
17309
0
            if (node->HostWindow)
17310
0
            {
17311
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X->%08X to Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, single_window->ID, single_window->Name);
17312
0
                single_window->Viewport = node->HostWindow->Viewport;
17313
0
                single_window->ViewportId = node->HostWindow->ViewportId;
17314
0
                if (node->HostWindow->ViewportOwned)
17315
0
                {
17316
0
                    single_window->Viewport->ID = single_window->ID;
17317
0
                    single_window->Viewport->Window = single_window;
17318
0
                    single_window->ViewportOwned = true;
17319
0
                }
17320
0
            }
17321
0
            node->RefViewportId = single_window->ViewportId;
17322
0
        }
17323
17324
0
        DockNodeHideHostWindow(node);
17325
0
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
17326
0
        node->WantCloseAll = false;
17327
0
        node->WantCloseTabId = 0;
17328
0
        node->HasCloseButton = node->HasWindowMenuButton = false;
17329
0
        node->LastFrameActive = g.FrameCount;
17330
17331
0
        if (node->WantMouseMove && node->Windows.Size == 1)
17332
0
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
17333
0
        return;
17334
0
    }
17335
17336
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
17337
    // while the expected visible window is resizing itself.
17338
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
17339
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
17340
    //   N+0: Begin(): window created (with no known size), node is created
17341
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
17342
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
17343
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
17344
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
17345
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
17346
0
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
17347
0
    {
17348
0
        IM_ASSERT(node->Windows.Size > 0);
17349
0
        ImGuiWindow* ref_window = NULL;
17350
0
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
17351
0
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
17352
0
        if (ref_window == NULL)
17353
0
            ref_window = node->Windows[0];
17354
0
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
17355
0
        {
17356
0
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
17357
0
            return;
17358
0
        }
17359
0
    }
17360
17361
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
17362
17363
    // Decide if the node will have a close button and a window menu button
17364
0
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
17365
0
    node->HasCloseButton = false;
17366
0
    for (ImGuiWindow* window : node->Windows)
17367
0
    {
17368
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
17369
0
        node->HasCloseButton |= window->HasCloseButton;
17370
0
        window->DockIsActive = (node->Windows.Size > 1);
17371
0
    }
17372
0
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
17373
0
        node->HasCloseButton = false;
17374
17375
    // Bind or create host window
17376
0
    ImGuiWindow* host_window = NULL;
17377
0
    bool beginned_into_host_window = false;
17378
0
    if (node->IsDockSpace())
17379
0
    {
17380
        // [Explicit root dockspace node]
17381
0
        IM_ASSERT(node->HostWindow);
17382
0
        host_window = node->HostWindow;
17383
0
    }
17384
0
    else
17385
0
    {
17386
        // [Automatic root or child nodes]
17387
0
        if (node->IsRootNode() && node->IsVisible)
17388
0
        {
17389
0
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
17390
17391
            // Sync Pos
17392
0
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
17393
0
                SetNextWindowPos(ref_window->Pos);
17394
0
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
17395
0
                SetNextWindowPos(node->Pos);
17396
17397
            // Sync Size
17398
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
17399
0
                SetNextWindowSize(ref_window->SizeFull);
17400
0
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
17401
0
                SetNextWindowSize(node->Size);
17402
17403
            // Sync Collapsed
17404
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
17405
0
                SetNextWindowCollapsed(ref_window->Collapsed);
17406
17407
            // Sync Viewport
17408
0
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
17409
0
                SetNextWindowViewport(ref_window->ViewportId);
17410
0
            else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0)
17411
0
                SetNextWindowViewport(node->RefViewportId);
17412
17413
0
            SetNextWindowClass(&node->WindowClass);
17414
17415
            // Begin into the host window
17416
0
            char window_label[20];
17417
0
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
17418
0
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
17419
0
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
17420
0
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
17421
0
            window_flags |= ImGuiWindowFlags_NoTitleBar;
17422
17423
0
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
17424
0
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
17425
0
            Begin(window_label, NULL, window_flags);
17426
0
            PopStyleVar();
17427
0
            beginned_into_host_window = true;
17428
17429
0
            host_window = g.CurrentWindow;
17430
0
            DockNodeSetupHostWindow(node, host_window);
17431
0
            host_window->DC.CursorPos = host_window->Pos;
17432
0
            node->Pos = host_window->Pos;
17433
0
            node->Size = host_window->Size;
17434
17435
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
17436
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
17437
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
17438
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
17439
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
17440
            // after the dock host window, losing their top-most status.
17441
0
            if (node->HostWindow->Appearing)
17442
0
                BringWindowToDisplayFront(node->HostWindow);
17443
17444
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17445
0
        }
17446
0
        else if (node->ParentNode)
17447
0
        {
17448
0
            node->HostWindow = host_window = node->ParentNode->HostWindow;
17449
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17450
0
        }
17451
0
        if (node->WantMouseMove && node->HostWindow)
17452
0
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
17453
0
    }
17454
0
    node->RefViewportId = 0; // Clear when we have a host window
17455
17456
    // Update focused node (the one whose title bar is highlight) within a node tree
17457
0
    if (node->IsSplitNode())
17458
0
        IM_ASSERT(node->TabBar == NULL);
17459
0
    if (node->IsRootNode())
17460
0
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
17461
0
            while (p_window != NULL && p_window->DockNode != NULL)
17462
0
            {
17463
0
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
17464
0
                if (p_node == node)
17465
0
                {
17466
0
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
17467
0
                    break;
17468
0
                }
17469
0
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
17470
0
            }
17471
17472
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
17473
0
    ImGuiDockNode* central_node = node->CentralNode;
17474
0
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
17475
0
    bool central_node_hole_register_hit_test_hole = central_node_hole;
17476
0
    if (central_node_hole)
17477
0
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
17478
0
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
17479
0
                central_node_hole_register_hit_test_hole = false;
17480
0
    if (central_node_hole_register_hit_test_hole)
17481
0
    {
17482
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
17483
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
17484
        // covering passthru node we'd have a gap on the edge not covered by the hole)
17485
0
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
17486
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
17487
0
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
17488
0
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
17489
0
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
17490
0
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
17491
0
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
17492
0
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
17493
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
17494
0
        if (central_node_hole && !hole_rect.IsInverted())
17495
0
        {
17496
0
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
17497
0
            if (host_window->ParentWindow)
17498
0
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
17499
0
        }
17500
0
    }
17501
17502
    // Update position/size, process and draw resizing splitters
17503
0
    if (node->IsRootNode() && host_window)
17504
0
    {
17505
0
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
17506
0
        PushStyleColor(ImGuiCol_Separator, g.Style.Colors[ImGuiCol_Border]);
17507
0
        PushStyleColor(ImGuiCol_SeparatorActive, g.Style.Colors[ImGuiCol_ResizeGripActive]);
17508
0
        PushStyleColor(ImGuiCol_SeparatorHovered, g.Style.Colors[ImGuiCol_ResizeGripHovered]);
17509
0
        DockNodeTreeUpdateSplitter(node);
17510
0
        PopStyleColor(3);
17511
0
    }
17512
17513
    // Draw empty node background (currently can only be the Central Node)
17514
0
    if (host_window && node->IsEmpty() && node->IsVisible)
17515
0
    {
17516
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17517
0
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
17518
0
        if (node->LastBgColor != 0)
17519
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
17520
0
        node->IsBgDrawnThisFrame = true;
17521
0
    }
17522
17523
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
17524
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
17525
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
17526
0
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
17527
0
    if (render_dockspace_bg && node->IsVisible)
17528
0
    {
17529
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17530
0
        if (central_node_hole)
17531
0
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
17532
0
        else
17533
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
17534
0
    }
17535
17536
    // Draw and populate Tab Bar
17537
0
    if (host_window)
17538
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
17539
0
    if (host_window && node->Windows.Size > 0)
17540
0
    {
17541
0
        DockNodeUpdateTabBar(node, host_window);
17542
0
    }
17543
0
    else
17544
0
    {
17545
0
        node->WantCloseAll = false;
17546
0
        node->WantCloseTabId = 0;
17547
0
        node->IsFocused = false;
17548
0
    }
17549
0
    if (node->TabBar && node->TabBar->SelectedTabId)
17550
0
        node->SelectedTabId = node->TabBar->SelectedTabId;
17551
0
    else if (node->Windows.Size > 0)
17552
0
        node->SelectedTabId = node->Windows[0]->TabId;
17553
17554
    // Draw payload drop target
17555
0
    if (host_window && node->IsVisible)
17556
0
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
17557
0
            BeginDockableDragDropTarget(host_window);
17558
17559
    // We update this after DockNodeUpdateTabBar()
17560
0
    node->LastFrameActive = g.FrameCount;
17561
17562
    // Recurse into children
17563
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
17564
0
    if (host_window)
17565
0
    {
17566
0
        if (node->ChildNodes[0])
17567
0
            DockNodeUpdate(node->ChildNodes[0]);
17568
0
        if (node->ChildNodes[1])
17569
0
            DockNodeUpdate(node->ChildNodes[1]);
17570
17571
        // Render outer borders last (after the tab bar)
17572
0
        if (node->IsRootNode())
17573
0
            RenderWindowOuterBorders(host_window);
17574
0
    }
17575
17576
    // End host window
17577
0
    if (beginned_into_host_window) //-V1020
17578
0
        End();
17579
0
}
17580
17581
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
17582
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
17583
0
{
17584
0
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
17585
0
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
17586
0
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
17587
0
        return d;
17588
0
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
17589
0
}
17590
17591
// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
17592
// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
17593
// Custom overrides may want to decorate, group, sort entries.
17594
// Please note those are internal structures: if you copy this expect occasional breakage.
17595
// (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler)
17596
void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
17597
0
{
17598
0
    IM_UNUSED(ctx);
17599
0
    if (tab_bar->Tabs.Size == 1)
17600
0
    {
17601
        // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
17602
0
        if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
17603
0
            node->WantHiddenTabBarToggle = true;
17604
0
    }
17605
0
    else
17606
0
    {
17607
        // Display a selectable list of windows in this docking node
17608
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
17609
0
        {
17610
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17611
0
            if (tab->Flags & ImGuiTabItemFlags_Button)
17612
0
                continue;
17613
0
            if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
17614
0
                TabBarQueueFocus(tab_bar, tab);
17615
0
            SameLine();
17616
0
            Text("   ");
17617
0
        }
17618
0
    }
17619
0
}
17620
17621
static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
17622
0
{
17623
    // Try to position the menu so it is more likely to stays within the same viewport
17624
0
    ImGuiContext& g = *GImGui;
17625
0
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
17626
0
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
17627
0
    else
17628
0
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
17629
0
    if (BeginPopup("#WindowMenu"))
17630
0
    {
17631
0
        node->IsFocused = true;
17632
0
        g.DockNodeWindowMenuHandler(&g, node, tab_bar);
17633
0
        EndPopup();
17634
0
    }
17635
0
}
17636
17637
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
17638
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
17639
0
{
17640
0
    if (node->TabBar == NULL || node->HostWindow == NULL)
17641
0
        return false;
17642
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
17643
0
        return false;
17644
0
    if (node->TabBar->ID == 0)
17645
0
        return false;
17646
0
    Begin(node->HostWindow->Name);
17647
0
    PushOverrideID(node->ID);
17648
0
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags);
17649
0
    IM_UNUSED(ret);
17650
0
    IM_ASSERT(ret);
17651
0
    return true;
17652
0
}
17653
17654
void ImGui::DockNodeEndAmendTabBar()
17655
0
{
17656
0
    EndTabBar();
17657
0
    PopID();
17658
0
    End();
17659
0
}
17660
17661
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
17662
0
{
17663
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
17664
0
    ImGuiContext& g = *GImGui;
17665
0
    if (g.NavWindowingTarget)
17666
0
        return (g.NavWindowingTarget->DockNode == node);
17667
17668
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
17669
0
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
17670
0
    {
17671
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
17672
0
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
17673
0
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
17674
0
            parent_window = parent_window->ParentWindow->RootWindow;
17675
0
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
17676
0
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
17677
0
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
17678
0
                return true;
17679
0
    }
17680
0
    return false;
17681
0
}
17682
17683
// Submit the tab bar corresponding to a dock node and various housekeeping details.
17684
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
17685
0
{
17686
0
    ImGuiContext& g = *GImGui;
17687
0
    ImGuiStyle& style = g.Style;
17688
17689
0
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
17690
0
    const bool closed_all = node->WantCloseAll && node_was_active;
17691
0
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
17692
0
    node->WantCloseAll = false;
17693
0
    node->WantCloseTabId = 0;
17694
17695
    // Decide if we should use a focused title bar color
17696
0
    bool is_focused = false;
17697
0
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
17698
0
    if (IsDockNodeTitleBarHighlighted(node, root_node))
17699
0
        is_focused = true;
17700
17701
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
17702
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
17703
0
    {
17704
0
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
17705
0
        node->IsFocused = is_focused;
17706
0
        if (is_focused)
17707
0
            node->LastFrameFocused = g.FrameCount;
17708
0
        if (node->VisibleWindow)
17709
0
        {
17710
            // Notify root of visible window (used to display title in OS task bar)
17711
0
            if (is_focused || root_node->VisibleWindow == NULL)
17712
0
                root_node->VisibleWindow = node->VisibleWindow;
17713
0
            if (node->TabBar)
17714
0
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
17715
0
        }
17716
0
        return;
17717
0
    }
17718
17719
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
17720
0
    bool backup_skip_item = host_window->SkipItems;
17721
0
    if (!node->IsDockSpace())
17722
0
    {
17723
0
        host_window->SkipItems = false;
17724
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
17725
0
    }
17726
17727
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
17728
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
17729
    // as docked windows themselves will override the stack with their own root ID.
17730
0
    PushOverrideID(node->ID);
17731
0
    ImGuiTabBar* tab_bar = node->TabBar;
17732
0
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
17733
0
    if (tab_bar == NULL)
17734
0
    {
17735
0
        DockNodeAddTabBar(node);
17736
0
        tab_bar = node->TabBar;
17737
0
    }
17738
17739
0
    ImGuiID focus_tab_id = 0;
17740
0
    node->IsFocused = is_focused;
17741
17742
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
17743
0
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
17744
17745
    // In a dock node, the Collapse Button turns into the Window Menu button.
17746
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
17747
0
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
17748
0
    {
17749
0
        ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
17750
0
        DockNodeWindowMenuUpdate(node, tab_bar);
17751
0
        if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
17752
0
            focus_tab_id = tab_bar->NextSelectedTabId;
17753
0
        is_focused |= node->IsFocused;
17754
0
    }
17755
17756
    // Layout
17757
0
    ImRect title_bar_rect, tab_bar_rect;
17758
0
    ImVec2 window_menu_button_pos;
17759
0
    ImVec2 close_button_pos;
17760
0
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
17761
17762
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
17763
0
    const int tabs_count_old = tab_bar->Tabs.Size;
17764
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17765
0
    {
17766
0
        ImGuiWindow* window = node->Windows[window_n];
17767
0
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
17768
0
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
17769
0
    }
17770
17771
    // Title bar
17772
0
    if (is_focused)
17773
0
        node->LastFrameFocused = g.FrameCount;
17774
0
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
17775
0
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), g.Style.DockingSeparatorSize);
17776
0
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
17777
17778
    // Docking/Collapse button
17779
0
    if (has_window_menu_button)
17780
0
    {
17781
0
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
17782
0
            OpenPopup("#WindowMenu");
17783
0
        if (IsItemActive())
17784
0
            focus_tab_id = tab_bar->SelectedTabId;
17785
0
        if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal) && g.HoveredIdTimer > 0.5f)
17786
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingDragToUndockOrMoveNode));
17787
0
    }
17788
17789
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
17790
0
    int tabs_unsorted_start = tab_bar->Tabs.Size;
17791
0
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
17792
0
    {
17793
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
17794
0
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
17795
0
        tabs_unsorted_start = tab_n;
17796
0
    }
17797
0
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
17798
0
    {
17799
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
17800
0
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
17801
0
        {
17802
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17803
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1);
17804
0
        }
17805
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1);
17806
0
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
17807
0
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
17808
0
    }
17809
17810
    // Apply NavWindow focus back to the tab bar
17811
0
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
17812
0
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
17813
17814
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
17815
0
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
17816
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
17817
0
    else if (tab_bar->Tabs.Size > tabs_count_old)
17818
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
17819
17820
    // Begin tab bar
17821
0
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
17822
0
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;// | ImGuiTabBarFlags_FittingPolicyScroll;
17823
0
    tab_bar_flags |= ImGuiTabBarFlags_DrawSelectedOverline;
17824
0
    if (!host_window->Collapsed && is_focused)
17825
0
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
17826
0
    tab_bar->ID = GetID("#TabBar");
17827
0
    tab_bar->SeparatorMinX = node->Pos.x + host_window->WindowBorderSize; // Separator cover the whole node width
17828
0
    tab_bar->SeparatorMaxX = node->Pos.x + node->Size.x - host_window->WindowBorderSize;
17829
0
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags);
17830
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
17831
17832
    // Backup style colors
17833
0
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
17834
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17835
0
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
17836
17837
    // Submit actual tabs
17838
0
    node->VisibleWindow = NULL;
17839
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17840
0
    {
17841
0
        ImGuiWindow* window = node->Windows[window_n];
17842
0
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
17843
0
            continue;
17844
0
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
17845
0
        {
17846
0
            ImGuiTabItemFlags tab_item_flags = 0;
17847
0
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
17848
0
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
17849
0
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
17850
0
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
17851
0
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
17852
17853
            // Apply stored style overrides for the window
17854
0
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17855
0
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
17856
17857
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
17858
0
            bool tab_open = true;
17859
0
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
17860
0
            if (!tab_open)
17861
0
                node->WantCloseTabId = window->TabId;
17862
0
            if (tab_bar->VisibleTabId == window->TabId)
17863
0
                node->VisibleWindow = window;
17864
17865
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
17866
0
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
17867
0
            window->DockTabItemRect = g.LastItemData.Rect;
17868
17869
            // Update navigation ID on menu layer
17870
0
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
17871
0
                host_window->NavLastIds[1] = window->TabId;
17872
0
        }
17873
0
    }
17874
17875
    // Restore style colors
17876
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17877
0
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
17878
17879
    // Notify root of visible window (used to display title in OS task bar)
17880
0
    if (node->VisibleWindow)
17881
0
        if (is_focused || root_node->VisibleWindow == NULL)
17882
0
            root_node->VisibleWindow = node->VisibleWindow;
17883
17884
    // Close button (after VisibleWindow was updated)
17885
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
17886
0
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
17887
0
    const bool close_button_is_visible = node->HasCloseButton;
17888
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
17889
0
    if (close_button_is_visible)
17890
0
    {
17891
0
        if (!close_button_is_enabled)
17892
0
        {
17893
0
            PushItemFlag(ImGuiItemFlags_Disabled, true);
17894
0
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
17895
0
        }
17896
0
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
17897
0
        {
17898
0
            node->WantCloseAll = true;
17899
0
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
17900
0
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
17901
0
        }
17902
        //if (IsItemActive())
17903
        //    focus_tab_id = tab_bar->SelectedTabId;
17904
0
        if (!close_button_is_enabled)
17905
0
        {
17906
0
            PopStyleColor();
17907
0
            PopItemFlag();
17908
0
        }
17909
0
    }
17910
17911
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
17912
    // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them.
17913
0
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
17914
0
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
17915
0
    {
17916
        // AllowOverlap mode required for appending into dock node tab bar,
17917
        // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
17918
0
        bool held;
17919
0
        KeepAliveID(title_bar_id);
17920
0
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowOverlap);
17921
0
        if (g.HoveredId == title_bar_id)
17922
0
        {
17923
0
            g.LastItemData.ID = title_bar_id;
17924
0
        }
17925
0
        if (held)
17926
0
        {
17927
0
            if (IsMouseClicked(0))
17928
0
                focus_tab_id = tab_bar->SelectedTabId;
17929
17930
            // Forward moving request to selected window
17931
0
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
17932
0
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false); // Undock from tab bar empty space
17933
0
        }
17934
0
    }
17935
17936
    // Forward focus from host node to selected window
17937
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
17938
    //    focus_tab_id = tab_bar->SelectedTabId;
17939
17940
    // When clicked on a tab we requested focus to the docked child
17941
    // This overrides the value set by "forward focus from host node to selected window".
17942
0
    if (tab_bar->NextSelectedTabId)
17943
0
        focus_tab_id = tab_bar->NextSelectedTabId;
17944
17945
    // Apply navigation focus
17946
0
    if (focus_tab_id != 0)
17947
0
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
17948
0
            if (tab->Window)
17949
0
            {
17950
0
                FocusWindow(tab->Window);
17951
0
                NavInitWindow(tab->Window, false);
17952
0
            }
17953
17954
0
    EndTabBar();
17955
0
    PopID();
17956
17957
    // Restore SkipItems flag
17958
0
    if (!node->IsDockSpace())
17959
0
    {
17960
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
17961
0
        host_window->SkipItems = backup_skip_item;
17962
0
    }
17963
0
}
17964
17965
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
17966
0
{
17967
0
    IM_ASSERT(node->TabBar == NULL);
17968
0
    node->TabBar = IM_NEW(ImGuiTabBar);
17969
0
}
17970
17971
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
17972
0
{
17973
0
    if (node->TabBar == NULL)
17974
0
        return;
17975
0
    IM_DELETE(node->TabBar);
17976
0
    node->TabBar = NULL;
17977
0
}
17978
17979
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
17980
0
{
17981
0
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
17982
0
        return false;
17983
17984
0
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
17985
0
    ImGuiWindowClass* payload_class = &payload->WindowClass;
17986
0
    if (host_class->ClassId != payload_class->ClassId)
17987
0
    {
17988
0
        bool pass = false;
17989
0
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
17990
0
            pass = true;
17991
0
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
17992
0
            pass = true;
17993
0
        if (!pass)
17994
0
            return false;
17995
0
    }
17996
17997
    // Prevent docking any window created above a popup
17998
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
17999
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
18000
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
18001
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
18002
0
    ImGuiContext& g = *GImGui;
18003
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
18004
0
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
18005
0
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
18006
0
                return false;
18007
18008
0
    return true;
18009
0
}
18010
18011
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
18012
0
{
18013
0
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
18014
0
        return true;
18015
18016
0
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
18017
0
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
18018
0
    {
18019
0
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
18020
0
        if (DockNodeIsDropAllowedOne(payload, host_window))
18021
0
            return true;
18022
0
    }
18023
0
    return false;
18024
0
}
18025
18026
// window menu button == collapse button when not in a dock node.
18027
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
18028
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
18029
0
{
18030
0
    ImGuiContext& g = *GImGui;
18031
0
    ImGuiStyle& style = g.Style;
18032
18033
0
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
18034
0
    if (out_title_rect) { *out_title_rect = r; }
18035
18036
0
    r.Min.x += style.WindowBorderSize;
18037
0
    r.Max.x -= style.WindowBorderSize;
18038
18039
0
    float button_sz = g.FontSize;
18040
0
    r.Min.x += style.FramePadding.x;
18041
0
    r.Max.x -= style.FramePadding.x;
18042
0
    ImVec2 window_menu_button_pos = ImVec2(r.Min.x, r.Min.y + style.FramePadding.y);
18043
0
    if (node->HasCloseButton)
18044
0
    {
18045
0
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
18046
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
18047
0
    }
18048
0
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
18049
0
    {
18050
0
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
18051
0
    }
18052
0
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
18053
0
    {
18054
0
        window_menu_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
18055
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
18056
0
    }
18057
0
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
18058
0
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
18059
0
}
18060
18061
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
18062
0
{
18063
0
    ImGuiContext& g = *GImGui;
18064
0
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
18065
0
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
18066
0
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
18067
0
    size_new[axis ^ 1] = size_old[axis ^ 1];
18068
18069
    // Distribute size on given axis (with a desired size or equally)
18070
0
    const float w_avail = size_old[axis] - dock_spacing;
18071
0
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
18072
0
    {
18073
0
        size_new[axis] = size_new_desired[axis];
18074
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
18075
0
    }
18076
0
    else
18077
0
    {
18078
0
        size_new[axis] = IM_TRUNC(w_avail * 0.5f);
18079
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
18080
0
    }
18081
18082
    // Position each node
18083
0
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
18084
0
    {
18085
0
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
18086
0
    }
18087
0
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
18088
0
    {
18089
0
        pos_new[axis] = pos_old[axis];
18090
0
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
18091
0
    }
18092
0
}
18093
18094
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
18095
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
18096
0
{
18097
0
    ImGuiContext& g = *GImGui;
18098
18099
0
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
18100
0
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
18101
0
    float hs_w; // Half-size, longer axis
18102
0
    float hs_h; // Half-size, smaller axis
18103
0
    ImVec2 off; // Distance from edge or center
18104
0
    if (outer_docking)
18105
0
    {
18106
        //hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
18107
        //hs_h = ImTrunc(hs_w * 0.15f);
18108
        //off = ImVec2(ImTrunc(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImTrunc(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
18109
0
        hs_w = ImTrunc(hs_for_central_nodes * 1.50f);
18110
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.80f);
18111
0
        off = ImTrunc(ImVec2(parent.GetWidth() * 0.5f - hs_h, parent.GetHeight() * 0.5f - hs_h));
18112
0
    }
18113
0
    else
18114
0
    {
18115
0
        hs_w = ImTrunc(hs_for_central_nodes);
18116
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.90f);
18117
0
        off = ImTrunc(ImVec2(hs_w * 2.40f, hs_w * 2.40f));
18118
0
    }
18119
18120
0
    ImVec2 c = ImTrunc(parent.GetCenter());
18121
0
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
18122
0
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
18123
0
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
18124
0
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
18125
0
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
18126
18127
0
    if (test_mouse_pos == NULL)
18128
0
        return false;
18129
18130
0
    ImRect hit_r = out_r;
18131
0
    if (!outer_docking)
18132
0
    {
18133
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
18134
0
        hit_r.Expand(ImTrunc(hs_w * 0.30f));
18135
0
        ImVec2 mouse_delta = (*test_mouse_pos - c);
18136
0
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
18137
0
        float r_threshold_center = hs_w * 1.4f;
18138
0
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
18139
0
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
18140
0
            return (dir == ImGuiDir_None);
18141
0
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
18142
0
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
18143
0
    }
18144
0
    return hit_r.Contains(*test_mouse_pos);
18145
0
}
18146
18147
// host_node may be NULL if the window doesn't have a DockNode already.
18148
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
18149
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
18150
0
{
18151
0
    ImGuiContext& g = *GImGui;
18152
18153
    // There is an edge case when docking into a dockspace which only has inactive nodes.
18154
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
18155
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
18156
0
    if (payload_node == NULL)
18157
0
        payload_node = payload_window->DockNodeAsHost;
18158
0
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
18159
0
    if (ref_node_for_rect)
18160
0
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
18161
18162
    // Filter, figure out where we are allowed to dock
18163
0
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
18164
0
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
18165
0
    data->IsCenterAvailable = true;
18166
0
    if (is_outer_docking)
18167
0
        data->IsCenterAvailable = false;
18168
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
18169
0
        data->IsCenterAvailable = false;
18170
0
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) && host_node->IsCentralNode())
18171
0
        data->IsCenterAvailable = false;
18172
0
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
18173
0
        data->IsCenterAvailable = false;
18174
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
18175
0
        data->IsCenterAvailable = false;
18176
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
18177
0
        data->IsCenterAvailable = false;
18178
18179
0
    data->IsSidesAvailable = true;
18180
0
    if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplit) || g.IO.ConfigDockingNoSplit)
18181
0
        data->IsSidesAvailable = false;
18182
0
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
18183
0
        data->IsSidesAvailable = false;
18184
0
    else if (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)
18185
0
        data->IsSidesAvailable = false;
18186
18187
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
18188
0
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
18189
0
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
18190
0
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
18191
0
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
18192
18193
    // Calculate drop shapes geometry for allowed splitting directions
18194
0
    IM_ASSERT(ImGuiDir_None == -1);
18195
0
    data->SplitNode = host_node;
18196
0
    data->SplitDir = ImGuiDir_None;
18197
0
    data->IsSplitDirExplicit = false;
18198
0
    if (!host_window->Collapsed)
18199
0
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
18200
0
        {
18201
0
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
18202
0
                continue;
18203
0
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
18204
0
                continue;
18205
0
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
18206
0
            {
18207
0
                data->SplitDir = (ImGuiDir)dir;
18208
0
                data->IsSplitDirExplicit = true;
18209
0
            }
18210
0
        }
18211
18212
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
18213
0
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
18214
0
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
18215
0
        data->IsDropAllowed = false;
18216
18217
    // Calculate split area
18218
0
    data->SplitRatio = 0.0f;
18219
0
    if (data->SplitDir != ImGuiDir_None)
18220
0
    {
18221
0
        ImGuiDir split_dir = data->SplitDir;
18222
0
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
18223
0
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
18224
0
        ImVec2 size_new, size_old = data->FutureNode.Size;
18225
0
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
18226
18227
        // Calculate split ratio so we can pass it down the docking request
18228
0
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
18229
0
        data->FutureNode.Pos = pos_new;
18230
0
        data->FutureNode.Size = size_new;
18231
0
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
18232
0
    }
18233
0
}
18234
18235
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
18236
0
{
18237
0
    ImGuiContext& g = *GImGui;
18238
0
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
18239
18240
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
18241
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
18242
0
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
18243
18244
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
18245
0
    int overlay_draw_lists_count = 0;
18246
0
    ImDrawList* overlay_draw_lists[2];
18247
0
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
18248
0
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
18249
0
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
18250
18251
    // Draw main preview rectangle
18252
0
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
18253
0
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
18254
0
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
18255
0
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
18256
18257
    // Display area preview
18258
0
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
18259
0
    if (data->IsDropAllowed)
18260
0
    {
18261
0
        ImRect overlay_rect = data->FutureNode.Rect();
18262
0
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
18263
0
            overlay_rect.Min.y += GetFrameHeight();
18264
0
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
18265
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
18266
0
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), g.Style.DockingSeparatorSize));
18267
0
    }
18268
18269
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
18270
0
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
18271
0
    {
18272
        // Compute target tab bar geometry so we can locate our preview tabs
18273
0
        ImRect tab_bar_rect;
18274
0
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
18275
0
        ImVec2 tab_pos = tab_bar_rect.Min;
18276
0
        if (host_node && host_node->TabBar)
18277
0
        {
18278
0
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
18279
0
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
18280
0
            else
18281
0
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
18282
0
        }
18283
0
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
18284
0
        {
18285
0
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
18286
0
        }
18287
18288
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
18289
0
        if (root_payload->DockNodeAsHost)
18290
0
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
18291
0
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
18292
0
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
18293
0
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
18294
0
        {
18295
            // DockNode's TabBar may have non-window Tabs manually appended by user
18296
0
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
18297
0
            if (tab_bar_with_payload && payload_window == NULL)
18298
0
                continue;
18299
0
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
18300
0
                continue;
18301
18302
            // Calculate the tab bounding box for each payload window
18303
0
            ImVec2 tab_size = TabItemCalcSize(payload_window);
18304
0
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
18305
0
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
18306
0
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
18307
0
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabSelected]);
18308
0
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
18309
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
18310
0
            {
18311
0
                ImGuiTabItemFlags tab_flags = (payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0;
18312
0
                if (!tab_bar_rect.Contains(tab_bb))
18313
0
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
18314
0
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
18315
0
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
18316
0
                if (!tab_bar_rect.Contains(tab_bb))
18317
0
                    overlay_draw_lists[overlay_n]->PopClipRect();
18318
0
            }
18319
0
            PopStyleColor();
18320
0
        }
18321
0
    }
18322
18323
    // Display drop boxes
18324
0
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
18325
0
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
18326
0
    {
18327
0
        if (!data->DropRectsDraw[dir + 1].IsInverted())
18328
0
        {
18329
0
            ImRect draw_r = data->DropRectsDraw[dir + 1];
18330
0
            ImRect draw_r_in = draw_r;
18331
0
            draw_r_in.Expand(-2.0f);
18332
0
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
18333
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
18334
0
            {
18335
0
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
18336
0
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
18337
0
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
18338
0
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
18339
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
18340
0
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
18341
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
18342
0
            }
18343
0
        }
18344
18345
        // Stop after ImGuiDir_None
18346
0
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoDockingSplit)) || g.IO.ConfigDockingNoSplit)
18347
0
            return;
18348
0
    }
18349
0
}
18350
18351
//-----------------------------------------------------------------------------
18352
// Docking: ImGuiDockNode Tree manipulation functions
18353
//-----------------------------------------------------------------------------
18354
// - DockNodeTreeSplit()
18355
// - DockNodeTreeMerge()
18356
// - DockNodeTreeUpdatePosSize()
18357
// - DockNodeTreeUpdateSplitterFindTouchingNode()
18358
// - DockNodeTreeUpdateSplitter()
18359
// - DockNodeTreeFindFallbackLeafNode()
18360
// - DockNodeTreeFindNodeByPos()
18361
//-----------------------------------------------------------------------------
18362
18363
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
18364
0
{
18365
0
    ImGuiContext& g = *GImGui;
18366
0
    IM_ASSERT(split_axis != ImGuiAxis_None);
18367
18368
0
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
18369
0
    child_0->ParentNode = parent_node;
18370
18371
0
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
18372
0
    child_1->ParentNode = parent_node;
18373
18374
0
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
18375
0
    DockNodeMoveChildNodes(child_inheritor, parent_node);
18376
0
    parent_node->ChildNodes[0] = child_0;
18377
0
    parent_node->ChildNodes[1] = child_1;
18378
0
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
18379
0
    parent_node->SplitAxis = split_axis;
18380
0
    parent_node->VisibleWindow = NULL;
18381
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18382
18383
0
    float size_avail = (parent_node->Size[split_axis] - g.Style.DockingSeparatorSize);
18384
0
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
18385
0
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
18386
0
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
18387
0
    child_0->SizeRef[split_axis] = ImTrunc(size_avail * split_ratio);
18388
0
    child_1->SizeRef[split_axis] = ImTrunc(size_avail - child_0->SizeRef[split_axis]);
18389
18390
0
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
18391
0
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
18392
0
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
18393
0
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
18394
18395
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
18396
0
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
18397
0
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
18398
0
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18399
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18400
0
    child_0->UpdateMergedFlags();
18401
0
    child_1->UpdateMergedFlags();
18402
0
    parent_node->UpdateMergedFlags();
18403
0
    if (child_inheritor->IsCentralNode())
18404
0
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
18405
0
}
18406
18407
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
18408
0
{
18409
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
18410
0
    ImGuiContext& g = *GImGui;
18411
0
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
18412
0
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
18413
0
    IM_ASSERT(child_0 || child_1);
18414
0
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
18415
0
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
18416
0
    {
18417
0
        IM_ASSERT(parent_node->TabBar == NULL);
18418
0
        IM_ASSERT(parent_node->Windows.Size == 0);
18419
0
    }
18420
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
18421
18422
0
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
18423
0
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
18424
0
    if (child_0)
18425
0
    {
18426
0
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
18427
0
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
18428
0
    }
18429
0
    if (child_1)
18430
0
    {
18431
0
        DockNodeMoveWindows(parent_node, child_1);
18432
0
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
18433
0
    }
18434
0
    DockNodeApplyPosSizeToWindows(parent_node);
18435
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
18436
0
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
18437
0
    parent_node->SizeRef = backup_last_explicit_size;
18438
18439
    // Flags transfer
18440
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
18441
0
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18442
0
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18443
0
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
18444
0
    parent_node->UpdateMergedFlags();
18445
18446
0
    if (child_0)
18447
0
    {
18448
0
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
18449
0
        IM_DELETE(child_0);
18450
0
    }
18451
0
    if (child_1)
18452
0
    {
18453
0
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
18454
0
        IM_DELETE(child_1);
18455
0
    }
18456
0
}
18457
18458
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
18459
// (Depth-first, Pre-Order)
18460
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
18461
0
{
18462
    // During the regular dock node update we write to all nodes.
18463
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
18464
0
    ImGuiContext& g = *GImGui;
18465
0
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
18466
0
    if (write_to_node)
18467
0
    {
18468
0
        node->Pos = pos;
18469
0
        node->Size = size;
18470
0
    }
18471
18472
0
    if (node->IsLeafNode())
18473
0
        return;
18474
18475
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
18476
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
18477
0
    ImVec2 child_0_pos = pos, child_1_pos = pos;
18478
0
    ImVec2 child_0_size = size, child_1_size = size;
18479
18480
0
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
18481
0
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
18482
0
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
18483
0
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
18484
18485
0
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
18486
0
    {
18487
0
        const float spacing = g.Style.DockingSeparatorSize;
18488
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
18489
0
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
18490
18491
        // Size allocation policy
18492
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
18493
0
        const float size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
18494
18495
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
18496
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc()
18497
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
18498
18499
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
18500
0
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
18501
0
        {
18502
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
18503
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
18504
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18505
0
        }
18506
0
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
18507
0
        {
18508
0
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
18509
0
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
18510
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18511
0
        }
18512
0
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
18513
0
        {
18514
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
18515
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
18516
0
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
18517
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImTrunc(size_avail * split_ratio);
18518
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
18519
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18520
0
        }
18521
18522
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
18523
0
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
18524
0
        {
18525
0
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
18526
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
18527
0
        }
18528
0
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
18529
0
        {
18530
0
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
18531
0
            child_0_size[axis] = (size_avail - child_1_size[axis]);
18532
0
        }
18533
0
        else
18534
0
        {
18535
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
18536
0
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
18537
0
            child_0_size[axis] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5f));
18538
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
18539
0
        }
18540
18541
0
        child_1_pos[axis] += spacing + child_0_size[axis];
18542
0
    }
18543
18544
0
    if (only_write_to_single_node == NULL)
18545
0
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
18546
18547
0
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
18548
0
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
18549
0
    if (child_0_recurse)
18550
0
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
18551
0
    if (child_1_recurse)
18552
0
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
18553
0
}
18554
18555
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
18556
0
{
18557
0
    if (node->IsLeafNode())
18558
0
    {
18559
0
        touching_nodes->push_back(node);
18560
0
        return;
18561
0
    }
18562
0
    if (node->ChildNodes[0]->IsVisible)
18563
0
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
18564
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
18565
0
    if (node->ChildNodes[1]->IsVisible)
18566
0
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
18567
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
18568
0
}
18569
18570
// (Depth-First, Pre-Order)
18571
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
18572
0
{
18573
0
    if (node->IsLeafNode())
18574
0
        return;
18575
18576
0
    ImGuiContext& g = *GImGui;
18577
18578
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
18579
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
18580
0
    if (child_0->IsVisible && child_1->IsVisible)
18581
0
    {
18582
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
18583
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
18584
0
        IM_ASSERT(axis != ImGuiAxis_None);
18585
0
        ImRect bb;
18586
0
        bb.Min = child_0->Pos;
18587
0
        bb.Max = child_1->Pos;
18588
0
        bb.Min[axis] += child_0->Size[axis];
18589
0
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
18590
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
18591
18592
0
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
18593
0
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
18594
0
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
18595
0
        {
18596
0
            ImGuiWindow* window = g.CurrentWindow;
18597
0
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
18598
0
        }
18599
0
        else
18600
0
        {
18601
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
18602
            //bb.Max[axis] -= 1;
18603
0
            PushID(node->ID);
18604
18605
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
18606
0
            ImVector<ImGuiDockNode*> touching_nodes[2];
18607
0
            float min_size = g.Style.WindowMinSize[axis];
18608
0
            float resize_limits[2];
18609
0
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
18610
0
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
18611
18612
0
            ImGuiID splitter_id = GetID("##Splitter");
18613
0
            if (g.ActiveId == splitter_id) // Only process when splitter is active
18614
0
            {
18615
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
18616
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
18617
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
18618
0
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
18619
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
18620
0
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
18621
18622
                // [DEBUG] Render touching nodes & limits
18623
                /*
18624
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18625
                for (int n = 0; n < 2; n++)
18626
                {
18627
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
18628
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
18629
                    if (axis == ImGuiAxis_X)
18630
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
18631
                    else
18632
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
18633
                }
18634
                */
18635
0
            }
18636
18637
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
18638
0
            float cur_size_0 = child_0->Size[axis];
18639
0
            float cur_size_1 = child_1->Size[axis];
18640
0
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
18641
0
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
18642
0
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
18643
0
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
18644
0
            {
18645
0
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
18646
0
                {
18647
0
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
18648
0
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
18649
0
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
18650
18651
                    // Lock the size of every node that is a sibling of the node we are touching
18652
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
18653
0
                    for (int side_n = 0; side_n < 2; side_n++)
18654
0
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
18655
0
                        {
18656
0
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
18657
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18658
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
18659
0
                            while (touching_node->ParentNode != node)
18660
0
                            {
18661
0
                                if (touching_node->ParentNode->SplitAxis == axis)
18662
0
                                {
18663
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
18664
0
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
18665
0
                                    node_to_preserve->WantLockSizeOnce = true;
18666
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
18667
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
18668
0
                                }
18669
0
                                touching_node = touching_node->ParentNode;
18670
0
                            }
18671
0
                        }
18672
18673
0
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
18674
0
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
18675
0
                    MarkIniSettingsDirty();
18676
0
                }
18677
0
            }
18678
0
            PopID();
18679
0
        }
18680
0
    }
18681
18682
0
    if (child_0->IsVisible)
18683
0
        DockNodeTreeUpdateSplitter(child_0);
18684
0
    if (child_1->IsVisible)
18685
0
        DockNodeTreeUpdateSplitter(child_1);
18686
0
}
18687
18688
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
18689
0
{
18690
0
    if (node->IsLeafNode())
18691
0
        return node;
18692
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
18693
0
        return leaf_node;
18694
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
18695
0
        return leaf_node;
18696
0
    return NULL;
18697
0
}
18698
18699
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
18700
0
{
18701
0
    if (!node->IsVisible)
18702
0
        return NULL;
18703
18704
0
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
18705
0
    ImRect r(node->Pos, node->Pos + node->Size);
18706
0
    r.Expand(dock_spacing * 0.5f);
18707
0
    bool inside = r.Contains(pos);
18708
0
    if (!inside)
18709
0
        return NULL;
18710
18711
0
    if (node->IsLeafNode())
18712
0
        return node;
18713
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
18714
0
        return hovered_node;
18715
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
18716
0
        return hovered_node;
18717
18718
    // This means we are hovering over the splitter/spacing of a parent node
18719
0
    return node;
18720
0
}
18721
18722
//-----------------------------------------------------------------------------
18723
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
18724
//-----------------------------------------------------------------------------
18725
// - SetWindowDock() [Internal]
18726
// - DockSpace()
18727
// - DockSpaceOverViewport()
18728
//-----------------------------------------------------------------------------
18729
18730
// [Internal] Called via SetNextWindowDockID()
18731
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
18732
0
{
18733
    // Test condition (NB: bit 0 is always true) and clear flags for next time
18734
0
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
18735
0
        return;
18736
0
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
18737
18738
0
    if (window->DockId == dock_id)
18739
0
        return;
18740
18741
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
18742
0
    ImGuiContext& g = *GImGui;
18743
0
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(&g, dock_id))
18744
0
        if (new_node->IsSplitNode())
18745
0
        {
18746
            // Policy: Find central node or latest focused node. We first move back to our root node.
18747
0
            new_node = DockNodeGetRootNode(new_node);
18748
0
            if (new_node->CentralNode)
18749
0
            {
18750
0
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
18751
0
                dock_id = new_node->CentralNode->ID;
18752
0
            }
18753
0
            else
18754
0
            {
18755
0
                dock_id = new_node->LastFocusedNodeId;
18756
0
            }
18757
0
        }
18758
18759
0
    if (window->DockId == dock_id)
18760
0
        return;
18761
18762
0
    if (window->DockNode)
18763
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
18764
0
    window->DockId = dock_id;
18765
0
}
18766
18767
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
18768
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
18769
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
18770
// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
18771
ImGuiID ImGui::DockSpace(ImGuiID dockspace_id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
18772
0
{
18773
0
    ImGuiContext& g = *GImGui;
18774
0
    ImGuiWindow* window = GetCurrentWindowRead();
18775
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18776
0
        return 0;
18777
18778
    // Early out if parent window is hidden/collapsed
18779
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
18780
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
18781
0
    if (window->SkipItems)
18782
0
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
18783
0
    if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
18784
0
        window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
18785
18786
0
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
18787
0
    IM_ASSERT(dockspace_id != 0);
18788
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, dockspace_id);
18789
0
    if (node == NULL)
18790
0
    {
18791
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", dockspace_id);
18792
0
        node = DockContextAddNode(&g, dockspace_id);
18793
0
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
18794
0
    }
18795
0
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
18796
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", dockspace_id, node->WindowClass.ClassId, window_class->ClassId);
18797
0
    node->SharedFlags = flags;
18798
0
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
18799
18800
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
18801
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
18802
0
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
18803
0
    {
18804
0
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
18805
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18806
0
        return dockspace_id;
18807
0
    }
18808
0
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18809
18810
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
18811
0
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
18812
0
    {
18813
0
        node->LastFrameAlive = g.FrameCount;
18814
0
        return dockspace_id;
18815
0
    }
18816
18817
0
    const ImVec2 content_avail = GetContentRegionAvail();
18818
0
    ImVec2 size = ImTrunc(size_arg);
18819
0
    if (size.x <= 0.0f)
18820
0
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
18821
0
    if (size.y <= 0.0f)
18822
0
        size.y = ImMax(content_avail.y + size.y, 4.0f);
18823
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18824
18825
0
    node->Pos = window->DC.CursorPos;
18826
0
    node->Size = node->SizeRef = size;
18827
0
    SetNextWindowPos(node->Pos);
18828
0
    SetNextWindowSize(node->Size);
18829
0
    g.NextWindowData.PosUndock = false;
18830
18831
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
18832
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
18833
0
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
18834
0
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
18835
0
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
18836
0
    window_flags |= ImGuiWindowFlags_NoBackground;
18837
18838
0
    char title[256];
18839
0
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, dockspace_id);
18840
18841
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
18842
0
    Begin(title, NULL, window_flags);
18843
0
    PopStyleVar();
18844
18845
0
    ImGuiWindow* host_window = g.CurrentWindow;
18846
0
    DockNodeSetupHostWindow(node, host_window);
18847
0
    host_window->ChildId = window->GetID(title);
18848
0
    node->OnlyNodeWithWindows = NULL;
18849
18850
0
    IM_ASSERT(node->IsRootNode());
18851
18852
    // We need to handle the rare case were a central node is missing.
18853
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
18854
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
18855
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
18856
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
18857
    // as it doesn't make sense for an empty dockspace to not have this property.
18858
0
    if (node->IsLeafNode() && !node->IsCentralNode())
18859
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18860
18861
    // Update the node
18862
0
    DockNodeUpdate(node);
18863
18864
0
    End();
18865
18866
0
    ImRect bb(node->Pos, node->Pos + size);
18867
0
    ItemSize(size);
18868
0
    ItemAdd(bb, dockspace_id, NULL, ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?)
18869
0
    if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild()
18870
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
18871
18872
0
    return dockspace_id;
18873
0
}
18874
18875
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
18876
// The limitation with this call is that your window won't have a local menu bar, but you can also use BeginMainMenuBar().
18877
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
18878
// If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
18879
ImGuiID ImGui::DockSpaceOverViewport(ImGuiID dockspace_id, const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
18880
0
{
18881
0
    if (viewport == NULL)
18882
0
        viewport = GetMainViewport();
18883
18884
    // Submit a window filling the entire viewport
18885
0
    SetNextWindowPos(viewport->WorkPos);
18886
0
    SetNextWindowSize(viewport->WorkSize);
18887
0
    SetNextWindowViewport(viewport->ID);
18888
18889
0
    ImGuiWindowFlags host_window_flags = 0;
18890
0
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
18891
0
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
18892
0
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
18893
0
        host_window_flags |= ImGuiWindowFlags_NoBackground;
18894
18895
0
    char label[32];
18896
0
    ImFormatString(label, IM_ARRAYSIZE(label), "WindowOverViewport_%08X", viewport->ID);
18897
18898
0
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
18899
0
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
18900
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
18901
0
    Begin(label, NULL, host_window_flags);
18902
0
    PopStyleVar(3);
18903
18904
    // Submit the dockspace
18905
0
    if (dockspace_id == 0)
18906
0
        dockspace_id = GetID("DockSpace");
18907
0
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
18908
18909
0
    End();
18910
18911
0
    return dockspace_id;
18912
0
}
18913
18914
//-----------------------------------------------------------------------------
18915
// Docking: Builder Functions
18916
//-----------------------------------------------------------------------------
18917
// Very early end-user API to manipulate dock nodes.
18918
// Only available in imgui_internal.h. Expect this API to change/break!
18919
// It is expected that those functions are all called _before_ the dockspace node submission.
18920
//-----------------------------------------------------------------------------
18921
// - DockBuilderDockWindow()
18922
// - DockBuilderGetNode()
18923
// - DockBuilderSetNodePos()
18924
// - DockBuilderSetNodeSize()
18925
// - DockBuilderAddNode()
18926
// - DockBuilderRemoveNode()
18927
// - DockBuilderRemoveNodeChildNodes()
18928
// - DockBuilderRemoveNodeDockedWindows()
18929
// - DockBuilderSplitNode()
18930
// - DockBuilderCopyNodeRec()
18931
// - DockBuilderCopyNode()
18932
// - DockBuilderCopyWindowSettings()
18933
// - DockBuilderCopyDockSpace()
18934
// - DockBuilderFinish()
18935
//-----------------------------------------------------------------------------
18936
18937
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
18938
0
{
18939
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
18940
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18941
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id);
18942
0
    ImGuiID window_id = ImHashStr(window_name);
18943
0
    if (ImGuiWindow* window = FindWindowByID(window_id))
18944
0
    {
18945
        // Apply to created window
18946
0
        ImGuiID prev_node_id = window->DockId;
18947
0
        SetWindowDock(window, node_id, ImGuiCond_Always);
18948
0
        if (window->DockId != prev_node_id)
18949
0
            window->DockOrder = -1;
18950
0
    }
18951
0
    else
18952
0
    {
18953
        // Apply to settings
18954
0
        ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
18955
0
        if (settings == NULL)
18956
0
            settings = CreateNewWindowSettings(window_name);
18957
0
        if (settings->DockId != node_id)
18958
0
            settings->DockOrder = -1;
18959
0
        settings->DockId = node_id;
18960
0
    }
18961
0
}
18962
18963
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
18964
0
{
18965
0
    ImGuiContext& g = *GImGui;
18966
0
    return DockContextFindNodeByID(&g, node_id);
18967
0
}
18968
18969
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
18970
0
{
18971
0
    ImGuiContext& g = *GImGui;
18972
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18973
0
    if (node == NULL)
18974
0
        return;
18975
0
    node->Pos = pos;
18976
0
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
18977
0
}
18978
18979
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
18980
0
{
18981
0
    ImGuiContext& g = *GImGui;
18982
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18983
0
    if (node == NULL)
18984
0
        return;
18985
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18986
0
    node->Size = node->SizeRef = size;
18987
0
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18988
0
}
18989
18990
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
18991
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
18992
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
18993
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
18994
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
18995
// - Use (id == 0) to let the system allocate a node identifier.
18996
// - Existing node with a same id will be removed.
18997
ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags)
18998
0
{
18999
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
19000
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags);
19001
19002
0
    if (node_id != 0)
19003
0
        DockBuilderRemoveNode(node_id);
19004
19005
0
    ImGuiDockNode* node = NULL;
19006
0
    if (flags & ImGuiDockNodeFlags_DockSpace)
19007
0
    {
19008
0
        DockSpace(node_id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
19009
0
        node = DockContextFindNodeByID(&g, node_id);
19010
0
    }
19011
0
    else
19012
0
    {
19013
0
        node = DockContextAddNode(&g, node_id);
19014
0
        node->SetLocalFlags(flags);
19015
0
    }
19016
0
    node->LastFrameAlive = g.FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
19017
0
    return node->ID;
19018
0
}
19019
19020
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
19021
0
{
19022
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
19023
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id);
19024
19025
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
19026
0
    if (node == NULL)
19027
0
        return;
19028
0
    DockBuilderRemoveNodeDockedWindows(node_id, true);
19029
0
    DockBuilderRemoveNodeChildNodes(node_id);
19030
    // Node may have moved or deleted if e.g. any merge happened
19031
0
    node = DockContextFindNodeByID(&g, node_id);
19032
0
    if (node == NULL)
19033
0
        return;
19034
0
    if (node->IsCentralNode() && node->ParentNode)
19035
0
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
19036
0
    DockContextRemoveNode(&g, node, true);
19037
0
}
19038
19039
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
19040
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
19041
0
{
19042
0
    ImGuiContext& g = *GImGui;
19043
0
    ImGuiDockContext* dc = &g.DockContext;
19044
19045
0
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(&g, root_id) : NULL;
19046
0
    if (root_id && root_node == NULL)
19047
0
        return;
19048
0
    bool has_central_node = false;
19049
19050
0
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
19051
0
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
19052
19053
    // Process active windows
19054
0
    ImVector<ImGuiDockNode*> nodes_to_remove;
19055
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
19056
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19057
0
        {
19058
0
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
19059
0
            if (want_removal)
19060
0
            {
19061
0
                if (node->IsCentralNode())
19062
0
                    has_central_node = true;
19063
0
                if (root_id != 0)
19064
0
                    DockContextQueueNotifyRemovedNode(&g, node);
19065
0
                if (root_node)
19066
0
                {
19067
0
                    DockNodeMoveWindows(root_node, node);
19068
0
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
19069
0
                }
19070
0
                nodes_to_remove.push_back(node);
19071
0
            }
19072
0
        }
19073
19074
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
19075
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
19076
0
    if (root_node)
19077
0
    {
19078
0
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
19079
0
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
19080
0
    }
19081
19082
    // Apply to settings
19083
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19084
0
        if (ImGuiID window_settings_dock_id = settings->DockId)
19085
0
            for (int n = 0; n < nodes_to_remove.Size; n++)
19086
0
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
19087
0
                {
19088
0
                    settings->DockId = root_id;
19089
0
                    break;
19090
0
                }
19091
19092
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
19093
0
    if (nodes_to_remove.Size > 1)
19094
0
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
19095
0
    for (int n = 0; n < nodes_to_remove.Size; n++)
19096
0
        DockContextRemoveNode(&g, nodes_to_remove[n], false);
19097
19098
0
    if (root_id == 0)
19099
0
    {
19100
0
        dc->Nodes.Clear();
19101
0
        dc->Requests.clear();
19102
0
    }
19103
0
    else if (has_central_node)
19104
0
    {
19105
0
        root_node->CentralNode = root_node;
19106
0
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
19107
0
    }
19108
0
}
19109
19110
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
19111
0
{
19112
    // Clear references in settings
19113
0
    ImGuiContext& g = *GImGui;
19114
0
    if (clear_settings_refs)
19115
0
    {
19116
0
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19117
0
        {
19118
0
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
19119
0
            if (!want_removal && settings->DockId != 0)
19120
0
                if (ImGuiDockNode* node = DockContextFindNodeByID(&g, settings->DockId))
19121
0
                    if (DockNodeGetRootNode(node)->ID == root_id)
19122
0
                        want_removal = true;
19123
0
            if (want_removal)
19124
0
                settings->DockId = 0;
19125
0
        }
19126
0
    }
19127
19128
    // Clear references in windows
19129
0
    for (int n = 0; n < g.Windows.Size; n++)
19130
0
    {
19131
0
        ImGuiWindow* window = g.Windows[n];
19132
0
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
19133
0
        if (want_removal)
19134
0
        {
19135
0
            const ImGuiID backup_dock_id = window->DockId;
19136
0
            IM_UNUSED(backup_dock_id);
19137
0
            DockContextProcessUndockWindow(&g, window, clear_settings_refs);
19138
0
            if (!clear_settings_refs)
19139
0
                IM_ASSERT(window->DockId == backup_dock_id);
19140
0
        }
19141
0
    }
19142
0
}
19143
19144
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
19145
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
19146
// FIXME-DOCK: We are not exposing nor using split_outer.
19147
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
19148
0
{
19149
0
    ImGuiContext& g = *GImGui;
19150
0
    IM_ASSERT(split_dir != ImGuiDir_None);
19151
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
19152
19153
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
19154
0
    if (node == NULL)
19155
0
    {
19156
0
        IM_ASSERT(node != NULL);
19157
0
        return 0;
19158
0
    }
19159
19160
0
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
19161
19162
0
    ImGuiDockRequest req;
19163
0
    req.Type = ImGuiDockRequestType_Split;
19164
0
    req.DockTargetWindow = NULL;
19165
0
    req.DockTargetNode = node;
19166
0
    req.DockPayload = NULL;
19167
0
    req.DockSplitDir = split_dir;
19168
0
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
19169
0
    req.DockSplitOuter = false;
19170
0
    DockContextProcessDock(&g, &req);
19171
19172
0
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
19173
0
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
19174
0
    if (out_id_at_dir)
19175
0
        *out_id_at_dir = id_at_dir;
19176
0
    if (out_id_at_opposite_dir)
19177
0
        *out_id_at_opposite_dir = id_at_opposite_dir;
19178
0
    return id_at_dir;
19179
0
}
19180
19181
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
19182
0
{
19183
0
    ImGuiContext& g = *GImGui;
19184
0
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
19185
0
    dst_node->SharedFlags = src_node->SharedFlags;
19186
0
    dst_node->LocalFlags = src_node->LocalFlags;
19187
0
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
19188
0
    dst_node->Pos = src_node->Pos;
19189
0
    dst_node->Size = src_node->Size;
19190
0
    dst_node->SizeRef = src_node->SizeRef;
19191
0
    dst_node->SplitAxis = src_node->SplitAxis;
19192
0
    dst_node->UpdateMergedFlags();
19193
19194
0
    out_node_remap_pairs->push_back(src_node->ID);
19195
0
    out_node_remap_pairs->push_back(dst_node->ID);
19196
19197
0
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
19198
0
        if (src_node->ChildNodes[child_n])
19199
0
        {
19200
0
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
19201
0
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
19202
0
        }
19203
19204
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
19205
0
    return dst_node;
19206
0
}
19207
19208
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
19209
0
{
19210
0
    ImGuiContext& g = *GImGui;
19211
0
    IM_ASSERT(src_node_id != 0);
19212
0
    IM_ASSERT(dst_node_id != 0);
19213
0
    IM_ASSERT(out_node_remap_pairs != NULL);
19214
19215
0
    DockBuilderRemoveNode(dst_node_id);
19216
19217
0
    ImGuiDockNode* src_node = DockContextFindNodeByID(&g, src_node_id);
19218
0
    IM_ASSERT(src_node != NULL);
19219
19220
0
    out_node_remap_pairs->clear();
19221
0
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
19222
19223
0
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
19224
0
}
19225
19226
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
19227
0
{
19228
0
    ImGuiWindow* src_window = FindWindowByName(src_name);
19229
0
    if (src_window == NULL)
19230
0
        return;
19231
0
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
19232
0
    {
19233
0
        dst_window->Pos = src_window->Pos;
19234
0
        dst_window->Size = src_window->Size;
19235
0
        dst_window->SizeFull = src_window->SizeFull;
19236
0
        dst_window->Collapsed = src_window->Collapsed;
19237
0
    }
19238
0
    else
19239
0
    {
19240
0
        ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
19241
0
        if (!dst_settings)
19242
0
            dst_settings = CreateNewWindowSettings(dst_name);
19243
0
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
19244
0
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
19245
0
        {
19246
0
            dst_settings->ViewportPos = window_pos_2ih;
19247
0
            dst_settings->ViewportId = src_window->ViewportId;
19248
0
            dst_settings->Pos = ImVec2ih(0, 0);
19249
0
        }
19250
0
        else
19251
0
        {
19252
0
            dst_settings->Pos = window_pos_2ih;
19253
0
        }
19254
0
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
19255
0
        dst_settings->Collapsed = src_window->Collapsed;
19256
0
    }
19257
0
}
19258
19259
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
19260
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
19261
0
{
19262
0
    ImGuiContext& g = *GImGui;
19263
0
    IM_ASSERT(src_dockspace_id != 0);
19264
0
    IM_ASSERT(dst_dockspace_id != 0);
19265
0
    IM_ASSERT(in_window_remap_pairs != NULL);
19266
0
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
19267
19268
    // Duplicate entire dock
19269
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
19270
    // whereas we could attempt to at least keep them together in a new, same floating node.
19271
0
    ImVector<ImGuiID> node_remap_pairs;
19272
0
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
19273
19274
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
19275
    // (The windows associated to src_dockspace_id are staying in place)
19276
0
    ImVector<ImGuiID> src_windows;
19277
0
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
19278
0
    {
19279
0
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
19280
0
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
19281
0
        ImGuiID src_window_id = ImHashStr(src_window_name);
19282
0
        src_windows.push_back(src_window_id);
19283
19284
        // Search in the remapping tables
19285
0
        ImGuiID src_dock_id = 0;
19286
0
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
19287
0
            src_dock_id = src_window->DockId;
19288
0
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
19289
0
            src_dock_id = src_window_settings->DockId;
19290
0
        ImGuiID dst_dock_id = 0;
19291
0
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
19292
0
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
19293
0
            {
19294
0
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
19295
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
19296
0
                break;
19297
0
            }
19298
19299
0
        if (dst_dock_id != 0)
19300
0
        {
19301
            // Docked windows gets redocked into the new node hierarchy.
19302
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
19303
0
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
19304
0
        }
19305
0
        else
19306
0
        {
19307
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
19308
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
19309
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
19310
0
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
19311
0
        }
19312
0
    }
19313
19314
    // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
19315
    // Find those windows and move to them to the cloned dock node. This may be optional?
19316
    // Dock those are a second step as undocking would invalidate source dock nodes.
19317
0
    struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
19318
0
    ImVector<DockRemainingWindowTask> dock_remaining_windows;
19319
0
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
19320
0
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
19321
0
        {
19322
0
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
19323
0
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
19324
0
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
19325
0
            {
19326
0
                ImGuiWindow* window = node->Windows[window_n];
19327
0
                if (src_windows.contains(window->ID))
19328
0
                    continue;
19329
19330
                // Docked windows gets redocked into the new node hierarchy.
19331
0
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
19332
0
                dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
19333
0
            }
19334
0
        }
19335
0
    for (const DockRemainingWindowTask& task : dock_remaining_windows)
19336
0
        DockBuilderDockWindow(task.Window->Name, task.DockId);
19337
0
}
19338
19339
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
19340
void ImGui::DockBuilderFinish(ImGuiID root_id)
19341
0
{
19342
0
    ImGuiContext& g = *GImGui;
19343
    //DockContextRebuild(&g);
19344
0
    DockContextBuildAddWindowsToNodes(&g, root_id);
19345
0
}
19346
19347
//-----------------------------------------------------------------------------
19348
// Docking: Begin/End Support Functions (called from Begin/End)
19349
//-----------------------------------------------------------------------------
19350
// - GetWindowAlwaysWantOwnTabBar()
19351
// - DockContextBindNodeToWindow()
19352
// - BeginDocked()
19353
// - BeginDockableDragDropSource()
19354
// - BeginDockableDragDropTarget()
19355
//-----------------------------------------------------------------------------
19356
19357
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
19358
127k
{
19359
127k
    ImGuiContext& g = *GImGui;
19360
127k
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
19361
0
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
19362
0
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
19363
0
                return true;
19364
127k
    return false;
19365
127k
}
19366
19367
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
19368
0
{
19369
0
    ImGuiContext& g = *ctx;
19370
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
19371
0
    IM_ASSERT(window->DockNode == NULL);
19372
19373
    // We should not be docking into a split node (SetWindowDock should avoid this)
19374
0
    if (node && node->IsSplitNode())
19375
0
    {
19376
0
        DockContextProcessUndockWindow(ctx, window);
19377
0
        return NULL;
19378
0
    }
19379
19380
    // Create node
19381
0
    if (node == NULL)
19382
0
    {
19383
0
        node = DockContextAddNode(ctx, window->DockId);
19384
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
19385
0
        node->LastFrameAlive = g.FrameCount;
19386
0
    }
19387
19388
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
19389
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
19390
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
19391
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
19392
0
    if (!node->IsVisible)
19393
0
    {
19394
0
        ImGuiDockNode* ancestor_node = node;
19395
0
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
19396
0
            ancestor_node = ancestor_node->ParentNode;
19397
0
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
19398
0
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
19399
0
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
19400
0
    }
19401
19402
    // Add window to node
19403
0
    bool node_was_visible = node->IsVisible;
19404
0
    DockNodeAddWindow(node, window, true);
19405
0
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
19406
0
    IM_ASSERT(node == window->DockNode);
19407
0
    return node;
19408
0
}
19409
19410
static void StoreDockStyleForWindow(ImGuiWindow* window)
19411
90
{
19412
90
    ImGuiContext& g = *GImGui;
19413
810
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19414
720
        window->DockStyle.Colors[color_n] = ImGui::ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
19415
90
}
19416
19417
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
19418
0
{
19419
0
    ImGuiContext& g = *GImGui;
19420
19421
    // Clear fields ahead so most early-out paths don't have to do it
19422
0
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
19423
19424
0
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
19425
0
    if (auto_dock_node)
19426
0
    {
19427
0
        if (window->DockId == 0)
19428
0
        {
19429
0
            IM_ASSERT(window->DockNode == NULL);
19430
0
            window->DockId = DockContextGenNodeID(&g);
19431
0
        }
19432
0
    }
19433
0
    else
19434
0
    {
19435
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
19436
0
        bool want_undock = false;
19437
0
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
19438
0
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
19439
0
        if (want_undock)
19440
0
        {
19441
0
            DockContextProcessUndockWindow(&g, window);
19442
0
            return;
19443
0
        }
19444
0
    }
19445
19446
    // Bind to our dock node
19447
0
    ImGuiDockNode* node = window->DockNode;
19448
0
    if (node != NULL)
19449
0
        IM_ASSERT(window->DockId == node->ID);
19450
0
    if (window->DockId != 0 && node == NULL)
19451
0
    {
19452
0
        node = DockContextBindNodeToWindow(&g, window);
19453
0
        if (node == NULL)
19454
0
            return;
19455
0
    }
19456
19457
#if 0
19458
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
19459
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
19460
    {
19461
        DockContextProcessUndockWindow(ctx, window);
19462
        return;
19463
    }
19464
#endif
19465
19466
    // Undock if our dockspace node disappeared
19467
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
19468
0
    if (node->LastFrameAlive < g.FrameCount)
19469
0
    {
19470
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
19471
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
19472
0
        if (root_node->LastFrameAlive < g.FrameCount)
19473
0
            DockContextProcessUndockWindow(&g, window);
19474
0
        else
19475
0
            window->DockIsActive = true;
19476
0
        return;
19477
0
    }
19478
19479
    // Store style overrides
19480
0
    StoreDockStyleForWindow(window);
19481
19482
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
19483
    // and never create neither a host window neither a tab bar.
19484
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
19485
0
    if (node->HostWindow == NULL)
19486
0
    {
19487
0
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
19488
0
            window->DockIsActive = true;
19489
0
        if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window
19490
0
            DockNodeHideWindowDuringHostWindowCreation(window);
19491
0
        return;
19492
0
    }
19493
19494
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
19495
0
    IM_ASSERT(node->HostWindow);
19496
0
    IM_ASSERT(node->IsLeafNode());
19497
0
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
19498
0
    node->State = ImGuiDockNodeState_HostWindowVisible;
19499
19500
    // Undock if we are submitted earlier than the host window
19501
0
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
19502
0
    {
19503
0
        DockContextProcessUndockWindow(&g, window);
19504
0
        return;
19505
0
    }
19506
19507
    // Position/Size window
19508
0
    SetNextWindowPos(node->Pos);
19509
0
    SetNextWindowSize(node->Size);
19510
0
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
19511
0
    window->DockIsActive = true;
19512
0
    window->DockNodeIsVisible = true;
19513
0
    window->DockTabIsVisible = false;
19514
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
19515
0
        return;
19516
19517
    // When the window is selected we mark it as visible.
19518
0
    if (node->VisibleWindow == window)
19519
0
        window->DockTabIsVisible = true;
19520
19521
    // Update window flag
19522
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
19523
0
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize;
19524
0
    window->ChildFlags |= ImGuiChildFlags_AlwaysUseWindowPadding;
19525
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
19526
0
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
19527
0
    else
19528
0
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
19529
19530
    // Save new dock order only if the window has been visible once already
19531
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
19532
0
    if (node->TabBar && window->WasActive)
19533
0
        window->DockOrder = (short)DockNodeGetTabOrder(window);
19534
19535
0
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
19536
0
        *p_open = false;
19537
19538
    // Update ChildId to allow returning from Child to Parent with Escape
19539
0
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
19540
0
    window->ChildId = parent_window->GetID(window->Name);
19541
0
}
19542
19543
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
19544
91
{
19545
91
    ImGuiContext& g = *GImGui;
19546
91
    IM_ASSERT(g.ActiveId == window->MoveId);
19547
91
    IM_ASSERT(g.MovingWindow == window);
19548
91
    IM_ASSERT(g.CurrentWindow == window);
19549
19550
    // 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking.
19551
91
    if (g.IO.ConfigDockingWithShift != g.IO.KeyShift)
19552
0
    {
19553
        // When ConfigDockingWithShift is set, display a tooltip to increase UI affordance.
19554
        // We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active
19555
        // (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function)
19556
0
        IM_ASSERT(g.NextWindowData.Flags == 0);
19557
0
        if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f)
19558
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingHoldShiftToDock));
19559
0
        return;
19560
0
    }
19561
19562
91
    g.LastItemData.ID = window->MoveId;
19563
91
    window = window->RootWindowDockTree;
19564
91
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
19565
91
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
19566
91
    ImGuiDragDropFlags drag_drop_flags = ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_PayloadAutoExpire | ImGuiDragDropFlags_PayloadNoCrossContext | ImGuiDragDropFlags_PayloadNoCrossProcess;
19567
91
    if (is_drag_docking && BeginDragDropSource(drag_drop_flags))
19568
90
    {
19569
90
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
19570
90
        EndDragDropSource();
19571
90
        StoreDockStyleForWindow(window); // Store style overrides while dragging (even when not docked) because docking preview may need it.
19572
90
    }
19573
91
}
19574
19575
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
19576
93
{
19577
93
    ImGuiContext& g = *GImGui;
19578
19579
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
19580
93
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
19581
93
    if (!g.DragDropActive)
19582
0
        return;
19583
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19584
93
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
19585
93
        return;
19586
19587
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
19588
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
19589
0
    const ImGuiPayload* payload = &g.DragDropPayload;
19590
0
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
19591
0
    {
19592
0
        EndDragDropTarget();
19593
0
        return;
19594
0
    }
19595
19596
0
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
19597
0
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
19598
0
    {
19599
        // Select target node
19600
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
19601
0
        bool dock_into_floating_window = false;
19602
0
        ImGuiDockNode* node = NULL;
19603
0
        if (window->DockNodeAsHost)
19604
0
        {
19605
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
19606
0
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
19607
19608
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
19609
            // In this case we need to fallback into any leaf mode, possibly the central node.
19610
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
19611
0
            if (node && node->IsDockSpace() && node->IsRootNode())
19612
0
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
19613
0
        }
19614
0
        else
19615
0
        {
19616
0
            if (window->DockNode)
19617
0
                node = window->DockNode;
19618
0
            else
19619
0
                dock_into_floating_window = true; // Dock into a regular window
19620
0
        }
19621
19622
0
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
19623
0
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
19624
19625
        // Preview docking request and find out split direction/ratio
19626
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
19627
0
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
19628
0
        if (do_preview && (node != NULL || dock_into_floating_window))
19629
0
        {
19630
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
19631
0
            ImGuiDockPreviewData split_inner;
19632
0
            ImGuiDockPreviewData split_outer;
19633
0
            ImGuiDockPreviewData* split_data = &split_inner;
19634
0
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
19635
0
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
19636
0
                {
19637
0
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
19638
0
                    if (split_outer.IsSplitDirExplicit)
19639
0
                        split_data = &split_outer;
19640
0
                }
19641
0
            if (!node || node->IsLeafNode())
19642
0
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
19643
0
            if (split_data == &split_outer)
19644
0
                split_inner.IsDropAllowed = false;
19645
19646
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
19647
0
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
19648
0
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
19649
19650
            // Queue docking request
19651
0
            if (split_data->IsDropAllowed && payload->IsDelivery())
19652
0
                DockContextQueueDock(&g, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
19653
0
        }
19654
0
    }
19655
0
    EndDragDropTarget();
19656
0
}
19657
19658
//-----------------------------------------------------------------------------
19659
// Docking: Settings
19660
//-----------------------------------------------------------------------------
19661
// - DockSettingsRenameNodeReferences()
19662
// - DockSettingsRemoveNodeReferences()
19663
// - DockSettingsFindNodeSettings()
19664
// - DockSettingsHandler_ApplyAll()
19665
// - DockSettingsHandler_ReadOpen()
19666
// - DockSettingsHandler_ReadLine()
19667
// - DockSettingsHandler_DockNodeToSettings()
19668
// - DockSettingsHandler_WriteAll()
19669
//-----------------------------------------------------------------------------
19670
19671
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
19672
0
{
19673
0
    ImGuiContext& g = *GImGui;
19674
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
19675
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
19676
0
    {
19677
0
        ImGuiWindow* window = g.Windows[window_n];
19678
0
        if (window->DockId == old_node_id && window->DockNode == NULL)
19679
0
            window->DockId = new_node_id;
19680
0
    }
19681
    //// FIXME-OPT: We could remove this loop by storing the index in the map
19682
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19683
0
        if (settings->DockId == old_node_id)
19684
0
            settings->DockId = new_node_id;
19685
0
}
19686
19687
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
19688
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
19689
0
{
19690
0
    ImGuiContext& g = *GImGui;
19691
0
    int found = 0;
19692
    //// FIXME-OPT: We could remove this loop by storing the index in the map
19693
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19694
0
        for (int node_n = 0; node_n < node_ids_count; node_n++)
19695
0
            if (settings->DockId == node_ids[node_n])
19696
0
            {
19697
0
                settings->DockId = 0;
19698
0
                settings->DockOrder = -1;
19699
0
                if (++found < node_ids_count)
19700
0
                    break;
19701
0
                return;
19702
0
            }
19703
0
}
19704
19705
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
19706
0
{
19707
    // FIXME-OPT
19708
0
    ImGuiDockContext* dc = &ctx->DockContext;
19709
0
    for (int n = 0; n < dc->NodesSettings.Size; n++)
19710
0
        if (dc->NodesSettings[n].ID == id)
19711
0
            return &dc->NodesSettings[n];
19712
0
    return NULL;
19713
0
}
19714
19715
// Clear settings data
19716
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
19717
0
{
19718
0
    ImGuiDockContext* dc = &ctx->DockContext;
19719
0
    dc->NodesSettings.clear();
19720
0
    DockContextClearNodes(ctx, 0, true);
19721
0
}
19722
19723
// Recreate nodes based on settings data
19724
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
19725
0
{
19726
    // Prune settings at boot time only
19727
0
    ImGuiDockContext* dc = &ctx->DockContext;
19728
0
    if (ctx->Windows.Size == 0)
19729
0
        DockContextPruneUnusedSettingsNodes(ctx);
19730
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
19731
0
    DockContextBuildAddWindowsToNodes(ctx, 0);
19732
0
}
19733
19734
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
19735
0
{
19736
0
    if (strcmp(name, "Data") != 0)
19737
0
        return NULL;
19738
0
    return (void*)1;
19739
0
}
19740
19741
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
19742
0
{
19743
0
    char c = 0;
19744
0
    int x = 0, y = 0;
19745
0
    int r = 0;
19746
19747
    // Parsing, e.g.
19748
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
19749
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
19750
    // Important: this code expect currently fields in a fixed order.
19751
0
    ImGuiDockNodeSettings node;
19752
0
    line = ImStrSkipBlank(line);
19753
0
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
19754
0
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
19755
0
    else return;
19756
0
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
19757
0
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
19758
0
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
19759
0
    if (node.ParentNodeId == 0)
19760
0
    {
19761
0
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
19762
0
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
19763
0
    }
19764
0
    else
19765
0
    {
19766
0
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
19767
0
    }
19768
0
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
19769
0
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
19770
0
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
19771
0
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
19772
0
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
19773
0
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
19774
0
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
19775
0
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
19776
0
    if (node.ParentNodeId != 0)
19777
0
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
19778
0
            node.Depth = parent_settings->Depth + 1;
19779
0
    ctx->DockContext.NodesSettings.push_back(node);
19780
0
}
19781
19782
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
19783
0
{
19784
0
    ImGuiDockNodeSettings node_settings;
19785
0
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
19786
0
    node_settings.ID = node->ID;
19787
0
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
19788
0
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
19789
0
    node_settings.SelectedTabId = node->SelectedTabId;
19790
0
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
19791
0
    node_settings.Depth = (char)depth;
19792
0
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
19793
0
    node_settings.Pos = ImVec2ih(node->Pos);
19794
0
    node_settings.Size = ImVec2ih(node->Size);
19795
0
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
19796
0
    dc->NodesSettings.push_back(node_settings);
19797
0
    if (node->ChildNodes[0])
19798
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
19799
0
    if (node->ChildNodes[1])
19800
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
19801
0
}
19802
19803
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
19804
0
{
19805
0
    ImGuiContext& g = *ctx;
19806
0
    ImGuiDockContext* dc = &ctx->DockContext;
19807
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
19808
0
        return;
19809
19810
    // Gather settings data
19811
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
19812
0
    dc->NodesSettings.resize(0);
19813
0
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
19814
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
19815
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19816
0
            if (node->IsRootNode())
19817
0
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
19818
19819
0
    int max_depth = 0;
19820
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19821
0
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
19822
19823
    // Write to text buffer
19824
0
    buf->appendf("[%s][Data]\n", handler->TypeName);
19825
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19826
0
    {
19827
0
        const int line_start_pos = buf->size(); (void)line_start_pos;
19828
0
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
19829
0
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
19830
0
        buf->appendf(" ID=0x%08X", node_settings->ID);
19831
0
        if (node_settings->ParentNodeId)
19832
0
        {
19833
0
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
19834
0
        }
19835
0
        else
19836
0
        {
19837
0
            if (node_settings->ParentWindowId)
19838
0
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
19839
0
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
19840
0
        }
19841
0
        if (node_settings->SplitAxis != ImGuiAxis_None)
19842
0
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
19843
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
19844
0
            buf->appendf(" NoResize=1");
19845
0
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
19846
0
            buf->appendf(" CentralNode=1");
19847
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
19848
0
            buf->appendf(" NoTabBar=1");
19849
0
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
19850
0
            buf->appendf(" HiddenTabBar=1");
19851
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
19852
0
            buf->appendf(" NoWindowMenuButton=1");
19853
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
19854
0
            buf->appendf(" NoCloseButton=1");
19855
0
        if (node_settings->SelectedTabId)
19856
0
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
19857
19858
        // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!)
19859
0
        if (g.IO.ConfigDebugIniSettings)
19860
0
            if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
19861
0
            {
19862
0
                buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
19863
0
                if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
19864
0
                    buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
19865
                // Iterate settings so we can give info about windows that didn't exist during the session.
19866
0
                int contains_window = 0;
19867
0
                for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19868
0
                    if (settings->DockId == node_settings->ID)
19869
0
                    {
19870
0
                        if (contains_window++ == 0)
19871
0
                            buf->appendf(" ; contains ");
19872
0
                        buf->appendf("'%s' ", settings->GetName());
19873
0
                    }
19874
0
            }
19875
19876
0
        buf->appendf("\n");
19877
0
    }
19878
0
    buf->appendf("\n");
19879
0
}
19880
19881
19882
//-----------------------------------------------------------------------------
19883
// [SECTION] PLATFORM DEPENDENT HELPERS
19884
//-----------------------------------------------------------------------------
19885
// - Default clipboard handlers
19886
// - Default shell function handlers
19887
// - Default IME handlers
19888
//-----------------------------------------------------------------------------
19889
19890
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
19891
19892
#ifdef _MSC_VER
19893
#pragma comment(lib, "user32")
19894
#pragma comment(lib, "kernel32")
19895
#endif
19896
19897
// Win32 clipboard implementation
19898
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
19899
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19900
{
19901
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19902
    g.ClipboardHandlerData.clear();
19903
    if (!::OpenClipboard(NULL))
19904
        return NULL;
19905
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
19906
    if (wbuf_handle == NULL)
19907
    {
19908
        ::CloseClipboard();
19909
        return NULL;
19910
    }
19911
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
19912
    {
19913
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
19914
        g.ClipboardHandlerData.resize(buf_len);
19915
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
19916
    }
19917
    ::GlobalUnlock(wbuf_handle);
19918
    ::CloseClipboard();
19919
    return g.ClipboardHandlerData.Data;
19920
}
19921
19922
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19923
{
19924
    if (!::OpenClipboard(NULL))
19925
        return;
19926
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
19927
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
19928
    if (wbuf_handle == NULL)
19929
    {
19930
        ::CloseClipboard();
19931
        return;
19932
    }
19933
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
19934
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
19935
    ::GlobalUnlock(wbuf_handle);
19936
    ::EmptyClipboard();
19937
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
19938
        ::GlobalFree(wbuf_handle);
19939
    ::CloseClipboard();
19940
}
19941
19942
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
19943
19944
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
19945
static PasteboardRef main_clipboard = 0;
19946
19947
// OSX clipboard implementation
19948
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
19949
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19950
{
19951
    if (!main_clipboard)
19952
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19953
    PasteboardClear(main_clipboard);
19954
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
19955
    if (cf_data)
19956
    {
19957
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
19958
        CFRelease(cf_data);
19959
    }
19960
}
19961
19962
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19963
{
19964
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19965
    if (!main_clipboard)
19966
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19967
    PasteboardSynchronize(main_clipboard);
19968
19969
    ItemCount item_count = 0;
19970
    PasteboardGetItemCount(main_clipboard, &item_count);
19971
    for (ItemCount i = 0; i < item_count; i++)
19972
    {
19973
        PasteboardItemID item_id = 0;
19974
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
19975
        CFArrayRef flavor_type_array = 0;
19976
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
19977
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
19978
        {
19979
            CFDataRef cf_data;
19980
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
19981
            {
19982
                g.ClipboardHandlerData.clear();
19983
                int length = (int)CFDataGetLength(cf_data);
19984
                g.ClipboardHandlerData.resize(length + 1);
19985
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
19986
                g.ClipboardHandlerData[length] = 0;
19987
                CFRelease(cf_data);
19988
                return g.ClipboardHandlerData.Data;
19989
            }
19990
        }
19991
    }
19992
    return NULL;
19993
}
19994
19995
#else
19996
19997
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
19998
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19999
0
{
20000
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
20001
0
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
20002
0
}
20003
20004
static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text)
20005
0
{
20006
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
20007
0
    g.ClipboardHandlerData.clear();
20008
0
    const char* text_end = text + strlen(text);
20009
0
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
20010
0
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
20011
0
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
20012
0
}
20013
20014
#endif // Default clipboard handlers
20015
20016
//-----------------------------------------------------------------------------
20017
20018
#ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
20019
#if defined(__APPLE__) && TARGET_OS_IPHONE
20020
#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
20021
#endif
20022
20023
#if defined(_WIN32) && defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
20024
#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
20025
#endif
20026
#endif
20027
20028
#ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
20029
#ifdef _WIN32
20030
#include <shellapi.h>   // ShellExecuteA()
20031
#ifdef _MSC_VER
20032
#pragma comment(lib, "shell32")
20033
#endif
20034
static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
20035
{
20036
    return (INT_PTR)::ShellExecuteA(NULL, "open", path, NULL, NULL, SW_SHOWDEFAULT) > 32;
20037
}
20038
#else
20039
#include <sys/wait.h>
20040
#include <unistd.h>
20041
static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
20042
0
{
20043
#if defined(__APPLE__)
20044
    const char* args[] { "open", "--", path, NULL };
20045
#else
20046
0
    const char* args[] { "xdg-open", path, NULL };
20047
0
#endif
20048
0
    pid_t pid = fork();
20049
0
    if (pid < 0)
20050
0
        return false;
20051
0
    if (!pid)
20052
0
    {
20053
0
        execvp(args[0], const_cast<char **>(args));
20054
0
        exit(-1);
20055
0
    }
20056
0
    else
20057
0
    {
20058
0
        int status;
20059
0
        waitpid(pid, &status, 0);
20060
0
        return WEXITSTATUS(status) == 0;
20061
0
    }
20062
0
}
20063
#endif
20064
#else
20065
static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char*) { return false; }
20066
#endif // Default shell handlers
20067
20068
//-----------------------------------------------------------------------------
20069
20070
// Win32 API IME support (for Asian languages, etc.)
20071
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
20072
20073
#include <imm.h>
20074
#ifdef _MSC_VER
20075
#pragma comment(lib, "imm32")
20076
#endif
20077
20078
static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data)
20079
{
20080
    // Notify OS Input Method Editor of text input position
20081
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
20082
    if (hwnd == 0)
20083
        return;
20084
20085
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
20086
    if (HIMC himc = ::ImmGetContext(hwnd))
20087
    {
20088
        COMPOSITIONFORM composition_form = {};
20089
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
20090
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
20091
        composition_form.dwStyle = CFS_FORCE_POSITION;
20092
        ::ImmSetCompositionWindow(himc, &composition_form);
20093
        CANDIDATEFORM candidate_form = {};
20094
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
20095
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
20096
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
20097
        ::ImmSetCandidateWindow(himc, &candidate_form);
20098
        ::ImmReleaseContext(hwnd, himc);
20099
    }
20100
}
20101
20102
#else
20103
20104
0
static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData*) {}
20105
20106
#endif // Default IME handlers
20107
20108
//-----------------------------------------------------------------------------
20109
// [SECTION] METRICS/DEBUGGER WINDOW
20110
//-----------------------------------------------------------------------------
20111
// - DebugRenderViewportThumbnail() [Internal]
20112
// - RenderViewportsThumbnails() [Internal]
20113
// - DebugTextEncoding()
20114
// - MetricsHelpMarker() [Internal]
20115
// - ShowFontAtlas() [Internal]
20116
// - ShowMetricsWindow()
20117
// - DebugNodeColumns() [Internal]
20118
// - DebugNodeDockNode() [Internal]
20119
// - DebugNodeDrawList() [Internal]
20120
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
20121
// - DebugNodeFont() [Internal]
20122
// - DebugNodeFontGlyph() [Internal]
20123
// - DebugNodeStorage() [Internal]
20124
// - DebugNodeTabBar() [Internal]
20125
// - DebugNodeViewport() [Internal]
20126
// - DebugNodeWindow() [Internal]
20127
// - DebugNodeWindowSettings() [Internal]
20128
// - DebugNodeWindowsList() [Internal]
20129
// - DebugNodeWindowsListByBeginStackParent() [Internal]
20130
//-----------------------------------------------------------------------------
20131
20132
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
20133
20134
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
20135
0
{
20136
0
    ImGuiContext& g = *GImGui;
20137
0
    ImGuiWindow* window = g.CurrentWindow;
20138
20139
0
    ImVec2 scale = bb.GetSize() / viewport->Size;
20140
0
    ImVec2 off = bb.Min - viewport->Pos * scale;
20141
0
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
20142
0
    window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
20143
0
    for (ImGuiWindow* thumb_window : g.Windows)
20144
0
    {
20145
0
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
20146
0
            continue;
20147
0
        if (thumb_window->Viewport != viewport)
20148
0
            continue;
20149
20150
0
        ImRect thumb_r = thumb_window->Rect();
20151
0
        ImRect title_r = thumb_window->TitleBarRect();
20152
0
        thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off +  thumb_r.Max * scale));
20153
0
        title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off +  ImVec2(title_r.Max.x, title_r.Min.y + title_r.GetHeight() * 3.0f) * scale)); // Exaggerate title bar height
20154
0
        thumb_r.ClipWithFull(bb);
20155
0
        title_r.ClipWithFull(bb);
20156
0
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
20157
0
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
20158
0
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
20159
0
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
20160
0
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
20161
0
    }
20162
0
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
20163
0
    if (viewport->ID == g.DebugMetricsConfig.HighlightViewportID)
20164
0
        window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
20165
0
}
20166
20167
static void RenderViewportsThumbnails()
20168
0
{
20169
0
    ImGuiContext& g = *GImGui;
20170
0
    ImGuiWindow* window = g.CurrentWindow;
20171
20172
    // Draw monitor and calculate their boundaries
20173
0
    float SCALE = 1.0f / 8.0f;
20174
0
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
20175
0
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
20176
0
        bb_full.Add(ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize));
20177
0
    ImVec2 p = window->DC.CursorPos;
20178
0
    ImVec2 off = p - bb_full.Min * SCALE;
20179
0
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
20180
0
    {
20181
0
        ImRect monitor_draw_bb(off + (monitor.MainPos) * SCALE, off + (monitor.MainPos + monitor.MainSize) * SCALE);
20182
0
        window->DrawList->AddRect(monitor_draw_bb.Min, monitor_draw_bb.Max, (g.DebugMetricsConfig.HighlightMonitorIdx == g.PlatformIO.Monitors.index_from_ptr(&monitor)) ? IM_COL32(255, 255, 0, 255) : ImGui::GetColorU32(ImGuiCol_Border), 4.0f);
20183
0
        window->DrawList->AddRectFilled(monitor_draw_bb.Min, monitor_draw_bb.Max, ImGui::GetColorU32(ImGuiCol_Border, 0.10f), 4.0f);
20184
0
    }
20185
20186
    // Draw viewports
20187
0
    for (ImGuiViewportP* viewport : g.Viewports)
20188
0
    {
20189
0
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
20190
0
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
20191
0
    }
20192
0
    ImGui::Dummy(bb_full.GetSize() * SCALE);
20193
0
}
20194
20195
static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
20196
0
{
20197
0
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
20198
0
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
20199
0
    return b->LastFocusedStampCount - a->LastFocusedStampCount;
20200
0
}
20201
20202
// Draw an arbitrary US keyboard layout to visualize translated keys
20203
void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
20204
0
{
20205
0
    const float scale = ImGui::GetFontSize() / 13.0f;
20206
0
    const ImVec2 key_size = ImVec2(35.0f, 35.0f) * scale;
20207
0
    const float  key_rounding = 3.0f * scale;
20208
0
    const ImVec2 key_face_size = ImVec2(25.0f, 25.0f) * scale;
20209
0
    const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f) * scale;
20210
0
    const float  key_face_rounding = 2.0f * scale;
20211
0
    const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f) * scale;
20212
0
    const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
20213
0
    const float  key_row_offset = 9.0f * scale;
20214
20215
0
    ImVec2 board_min = GetCursorScreenPos();
20216
0
    ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
20217
0
    ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
20218
20219
0
    struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
20220
0
    const KeyLayoutData keys_to_display[] =
20221
0
    {
20222
0
        { 0, 0, "", ImGuiKey_Tab },      { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
20223
0
        { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
20224
0
        { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
20225
0
    };
20226
20227
    // Elements rendered manually via ImDrawList API are not clipped automatically.
20228
    // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
20229
0
    Dummy(board_max - board_min);
20230
0
    if (!IsItemVisible())
20231
0
        return;
20232
0
    draw_list->PushClipRect(board_min, board_max, true);
20233
0
    for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
20234
0
    {
20235
0
        const KeyLayoutData* key_data = &keys_to_display[n];
20236
0
        ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
20237
0
        ImVec2 key_max = key_min + key_size;
20238
0
        draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
20239
0
        draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
20240
0
        ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
20241
0
        ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
20242
0
        draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
20243
0
        draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
20244
0
        ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
20245
0
        draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
20246
0
        if (IsKeyDown(key_data->Key))
20247
0
            draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
20248
0
    }
20249
0
    draw_list->PopClipRect();
20250
0
}
20251
20252
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
20253
void ImGui::DebugTextEncoding(const char* str)
20254
0
{
20255
0
    Text("Text: \"%s\"", str);
20256
0
    if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
20257
0
        return;
20258
0
    TableSetupColumn("Offset");
20259
0
    TableSetupColumn("UTF-8");
20260
0
    TableSetupColumn("Glyph");
20261
0
    TableSetupColumn("Codepoint");
20262
0
    TableHeadersRow();
20263
0
    for (const char* p = str; *p != 0; )
20264
0
    {
20265
0
        unsigned int c;
20266
0
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
20267
0
        TableNextColumn();
20268
0
        Text("%d", (int)(p - str));
20269
0
        TableNextColumn();
20270
0
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
20271
0
        {
20272
0
            if (byte_index > 0)
20273
0
                SameLine();
20274
0
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
20275
0
        }
20276
0
        TableNextColumn();
20277
0
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
20278
0
            TextUnformatted(p, p + c_utf8_len);
20279
0
        else
20280
0
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
20281
0
        TableNextColumn();
20282
0
        Text("U+%04X", (int)c);
20283
0
        p += c_utf8_len;
20284
0
    }
20285
0
    EndTable();
20286
0
}
20287
20288
static void DebugFlashStyleColorStop()
20289
0
{
20290
0
    ImGuiContext& g = *GImGui;
20291
0
    if (g.DebugFlashStyleColorIdx != ImGuiCol_COUNT)
20292
0
        g.Style.Colors[g.DebugFlashStyleColorIdx] = g.DebugFlashStyleColorBackup;
20293
0
    g.DebugFlashStyleColorIdx = ImGuiCol_COUNT;
20294
0
}
20295
20296
// Flash a given style color for some + inhibit modifications of this color via PushStyleColor() calls.
20297
void ImGui::DebugFlashStyleColor(ImGuiCol idx)
20298
0
{
20299
0
    ImGuiContext& g = *GImGui;
20300
0
    DebugFlashStyleColorStop();
20301
0
    g.DebugFlashStyleColorTime = 0.5f;
20302
0
    g.DebugFlashStyleColorIdx = idx;
20303
0
    g.DebugFlashStyleColorBackup = g.Style.Colors[idx];
20304
0
}
20305
20306
void ImGui::UpdateDebugToolFlashStyleColor()
20307
58.4k
{
20308
58.4k
    ImGuiContext& g = *GImGui;
20309
58.4k
    if (g.DebugFlashStyleColorTime <= 0.0f)
20310
58.4k
        return;
20311
0
    ColorConvertHSVtoRGB(cosf(g.DebugFlashStyleColorTime * 6.0f) * 0.5f + 0.5f, 0.5f, 0.5f, g.Style.Colors[g.DebugFlashStyleColorIdx].x, g.Style.Colors[g.DebugFlashStyleColorIdx].y, g.Style.Colors[g.DebugFlashStyleColorIdx].z);
20312
0
    g.Style.Colors[g.DebugFlashStyleColorIdx].w = 1.0f;
20313
0
    if ((g.DebugFlashStyleColorTime -= g.IO.DeltaTime) <= 0.0f)
20314
0
        DebugFlashStyleColorStop();
20315
0
}
20316
20317
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
20318
static void MetricsHelpMarker(const char* desc)
20319
0
{
20320
0
    ImGui::TextDisabled("(?)");
20321
0
    if (ImGui::BeginItemTooltip())
20322
0
    {
20323
0
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
20324
0
        ImGui::TextUnformatted(desc);
20325
0
        ImGui::PopTextWrapPos();
20326
0
        ImGui::EndTooltip();
20327
0
    }
20328
0
}
20329
20330
// [DEBUG] List fonts in a font atlas and display its texture
20331
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
20332
0
{
20333
0
    for (ImFont* font : atlas->Fonts)
20334
0
    {
20335
0
        PushID(font);
20336
0
        DebugNodeFont(font);
20337
0
        PopID();
20338
0
    }
20339
0
    if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
20340
0
    {
20341
0
        ImGuiContext& g = *GImGui;
20342
0
        ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
20343
0
        Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
20344
0
        ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
20345
0
        ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
20346
0
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
20347
0
        TreePop();
20348
0
    }
20349
0
}
20350
20351
void ImGui::ShowMetricsWindow(bool* p_open)
20352
0
{
20353
0
    ImGuiContext& g = *GImGui;
20354
0
    ImGuiIO& io = g.IO;
20355
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
20356
0
    if (cfg->ShowDebugLog)
20357
0
        ShowDebugLogWindow(&cfg->ShowDebugLog);
20358
0
    if (cfg->ShowIDStackTool)
20359
0
        ShowIDStackToolWindow(&cfg->ShowIDStackTool);
20360
20361
0
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
20362
0
    {
20363
0
        End();
20364
0
        return;
20365
0
    }
20366
20367
    // [DEBUG] Clear debug breaks hooks after exactly one cycle.
20368
0
    DebugBreakClearData();
20369
20370
    // Basic info
20371
0
    Text("Dear ImGui %s", GetVersion());
20372
0
    if (g.ContextName[0] != 0)
20373
0
    {
20374
0
        SameLine();
20375
0
        Text("(Context Name: \"%s\")", g.ContextName);
20376
0
    }
20377
0
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
20378
0
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
20379
0
    Text("%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
20380
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
20381
20382
0
    Separator();
20383
20384
    // Debugging enums
20385
0
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
20386
0
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
20387
0
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
20388
0
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
20389
0
    if (cfg->ShowWindowsRectsType < 0)
20390
0
        cfg->ShowWindowsRectsType = WRT_WorkRect;
20391
0
    if (cfg->ShowTablesRectsType < 0)
20392
0
        cfg->ShowTablesRectsType = TRT_WorkRect;
20393
20394
0
    struct Funcs
20395
0
    {
20396
0
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
20397
0
        {
20398
0
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
20399
0
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
20400
0
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
20401
0
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
20402
0
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
20403
0
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
20404
0
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
20405
0
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
20406
0
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
20407
0
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
20408
0
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); } // Note: y1/y2 not always accurate
20409
0
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); }
20410
0
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
20411
0
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
20412
0
            IM_ASSERT(0);
20413
0
            return ImRect();
20414
0
        }
20415
20416
0
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
20417
0
        {
20418
0
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
20419
0
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
20420
0
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
20421
0
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
20422
0
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
20423
0
            else if (rect_type == WRT_Content)              { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
20424
0
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
20425
0
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
20426
0
            IM_ASSERT(0);
20427
0
            return ImRect();
20428
0
        }
20429
0
    };
20430
20431
    // Tools
20432
0
    if (TreeNode("Tools"))
20433
0
    {
20434
        // Debug Break features
20435
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
20436
0
        SeparatorTextEx(0, "Debug breaks", NULL, CalcTextSize("(?)").x + g.Style.SeparatorTextPadding.x);
20437
0
        SameLine();
20438
0
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
20439
0
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
20440
0
            DebugStartItemPicker();
20441
0
        Checkbox("Show \"Debug Break\" buttons in other sections (io.ConfigDebugIsDebuggerPresent)", &g.IO.ConfigDebugIsDebuggerPresent);
20442
20443
0
        SeparatorText("Visualize");
20444
20445
0
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
20446
0
        SameLine();
20447
0
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
20448
20449
0
        Checkbox("Show ID Stack Tool", &cfg->ShowIDStackTool);
20450
0
        SameLine();
20451
0
        MetricsHelpMarker("You can also call ImGui::ShowIDStackToolWindow() from your code.");
20452
20453
0
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
20454
0
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
20455
0
        SameLine();
20456
0
        SetNextItemWidth(GetFontSize() * 12);
20457
0
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
20458
0
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
20459
0
        {
20460
0
            BulletText("'%s':", g.NavWindow->Name);
20461
0
            Indent();
20462
0
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
20463
0
            {
20464
0
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
20465
0
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
20466
0
            }
20467
0
            Unindent();
20468
0
        }
20469
20470
0
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
20471
0
        SameLine();
20472
0
        SetNextItemWidth(GetFontSize() * 12);
20473
0
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
20474
0
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
20475
0
        {
20476
0
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20477
0
            {
20478
0
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
20479
0
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
20480
0
                    continue;
20481
20482
0
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
20483
0
                if (IsItemHovered())
20484
0
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20485
0
                Indent();
20486
0
                char buf[128];
20487
0
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
20488
0
                {
20489
0
                    if (rect_n >= TRT_ColumnsRect)
20490
0
                    {
20491
0
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
20492
0
                            continue;
20493
0
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20494
0
                        {
20495
0
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
20496
0
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
20497
0
                            Selectable(buf);
20498
0
                            if (IsItemHovered())
20499
0
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20500
0
                        }
20501
0
                    }
20502
0
                    else
20503
0
                    {
20504
0
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
20505
0
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
20506
0
                        Selectable(buf);
20507
0
                        if (IsItemHovered())
20508
0
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20509
0
                    }
20510
0
                }
20511
0
                Unindent();
20512
0
            }
20513
0
        }
20514
0
        Checkbox("Show groups rectangles", &g.DebugShowGroupRects); // Storing in context as this is used by group code and prefers to be in hot-data
20515
20516
0
        SeparatorText("Validate");
20517
20518
0
        Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
20519
0
        SameLine();
20520
0
        MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
20521
20522
0
        Checkbox("UTF-8 Encoding viewer", &cfg->ShowTextEncodingViewer);
20523
0
        SameLine();
20524
0
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
20525
0
        if (cfg->ShowTextEncodingViewer)
20526
0
        {
20527
0
            static char buf[64] = "";
20528
0
            SetNextItemWidth(-FLT_MIN);
20529
0
            InputText("##DebugTextEncodingBuf", buf, IM_ARRAYSIZE(buf));
20530
0
            if (buf[0] != 0)
20531
0
                DebugTextEncoding(buf);
20532
0
        }
20533
20534
0
        TreePop();
20535
0
    }
20536
20537
    // Windows
20538
0
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
20539
0
    {
20540
        //SetNextItemOpen(true, ImGuiCond_Once);
20541
0
        DebugNodeWindowsList(&g.Windows, "By display order");
20542
0
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
20543
0
        if (TreeNode("By submission order (begin stack)"))
20544
0
        {
20545
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
20546
0
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
20547
0
            temp_buffer.resize(0);
20548
0
            for (ImGuiWindow* window : g.Windows)
20549
0
                if (window->LastFrameActive + 1 >= g.FrameCount)
20550
0
                    temp_buffer.push_back(window);
20551
0
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
20552
0
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
20553
0
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
20554
0
            TreePop();
20555
0
        }
20556
20557
0
        TreePop();
20558
0
    }
20559
20560
    // DrawLists
20561
0
    int drawlist_count = 0;
20562
0
    for (ImGuiViewportP* viewport : g.Viewports)
20563
0
        drawlist_count += viewport->DrawDataP.CmdLists.Size;
20564
0
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
20565
0
    {
20566
0
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
20567
0
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
20568
0
        for (ImGuiViewportP* viewport : g.Viewports)
20569
0
        {
20570
0
            bool viewport_has_drawlist = false;
20571
0
            for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
20572
0
            {
20573
0
                if (!viewport_has_drawlist)
20574
0
                    Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
20575
0
                viewport_has_drawlist = true;
20576
0
                DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
20577
0
            }
20578
0
        }
20579
0
        TreePop();
20580
0
    }
20581
20582
    // Viewports
20583
0
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
20584
0
    {
20585
0
        cfg->HighlightMonitorIdx = -1;
20586
0
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
20587
0
        SameLine();
20588
0
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
20589
0
        if (open)
20590
0
        {
20591
0
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
20592
0
            {
20593
0
                const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
20594
0
                BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
20595
0
                    i, mon.DpiScale * 100.0f,
20596
0
                    mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
20597
0
                    mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
20598
0
                if (IsItemHovered())
20599
0
                    cfg->HighlightMonitorIdx = i;
20600
0
            }
20601
0
            TreePop();
20602
0
        }
20603
20604
0
        SetNextItemOpen(true, ImGuiCond_Once);
20605
0
        if (TreeNode("Windows Minimap"))
20606
0
        {
20607
0
            RenderViewportsThumbnails();
20608
0
            TreePop();
20609
0
        }
20610
0
        cfg->HighlightViewportID = 0;
20611
20612
0
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20613
0
        if (TreeNode("Inferred Z order (front-to-back)"))
20614
0
        {
20615
0
            static ImVector<ImGuiViewportP*> viewports;
20616
0
            viewports.resize(g.Viewports.Size);
20617
0
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
20618
0
            if (viewports.Size > 1)
20619
0
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount);
20620
0
            for (ImGuiViewportP* viewport : viewports)
20621
0
            {
20622
0
                BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
20623
0
                    viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
20624
0
                    (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
20625
0
                    viewport->Window ? viewport->Window->Name : "N/A");
20626
0
                if (IsItemHovered())
20627
0
                    cfg->HighlightViewportID = viewport->ID;
20628
0
            }
20629
0
            TreePop();
20630
0
        }
20631
20632
0
        for (ImGuiViewportP* viewport : g.Viewports)
20633
0
            DebugNodeViewport(viewport);
20634
0
        TreePop();
20635
0
    }
20636
20637
    // Details for Popups
20638
0
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
20639
0
    {
20640
0
        for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
20641
0
        {
20642
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
20643
0
            ImGuiWindow* window = popup_data.Window;
20644
0
            BulletText("PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'",
20645
0
                popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
20646
0
                popup_data.RestoreNavWindow ? popup_data.RestoreNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
20647
0
        }
20648
0
        TreePop();
20649
0
    }
20650
20651
    // Details for TabBars
20652
0
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
20653
0
    {
20654
0
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
20655
0
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
20656
0
            {
20657
0
                PushID(tab_bar);
20658
0
                DebugNodeTabBar(tab_bar, "TabBar");
20659
0
                PopID();
20660
0
            }
20661
0
        TreePop();
20662
0
    }
20663
20664
    // Details for Tables
20665
0
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
20666
0
    {
20667
0
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
20668
0
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
20669
0
                DebugNodeTable(table);
20670
0
        TreePop();
20671
0
    }
20672
20673
    // Details for Fonts
20674
0
    ImFontAtlas* atlas = g.IO.Fonts;
20675
0
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
20676
0
    {
20677
0
        ShowFontAtlas(atlas);
20678
0
        TreePop();
20679
0
    }
20680
20681
    // Details for InputText
20682
0
    if (TreeNode("InputText"))
20683
0
    {
20684
0
        DebugNodeInputTextState(&g.InputTextState);
20685
0
        TreePop();
20686
0
    }
20687
20688
    // Details for TypingSelect
20689
0
    if (TreeNode("TypingSelect", "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
20690
0
    {
20691
0
        DebugNodeTypingSelectState(&g.TypingSelectState);
20692
0
        TreePop();
20693
0
    }
20694
20695
    // Details for MultiSelect
20696
0
    if (TreeNode("MultiSelect", "MultiSelect (%d)", g.MultiSelectStorage.GetAliveCount()))
20697
0
    {
20698
0
        ImGuiBoxSelectState* bs = &g.BoxSelectState;
20699
0
        BulletText("BoxSelect ID=0x%08X, Starting = %d, Active %d", bs->ID, bs->IsStarting, bs->IsActive);
20700
0
        for (int n = 0; n < g.MultiSelectStorage.GetMapSize(); n++)
20701
0
            if (ImGuiMultiSelectState* state = g.MultiSelectStorage.TryGetMapData(n))
20702
0
                DebugNodeMultiSelectState(state);
20703
0
        TreePop();
20704
0
    }
20705
20706
    // Details for Docking
20707
0
#ifdef IMGUI_HAS_DOCK
20708
0
    if (TreeNode("Docking"))
20709
0
    {
20710
0
        static bool root_nodes_only = true;
20711
0
        ImGuiDockContext* dc = &g.DockContext;
20712
0
        Checkbox("List root nodes", &root_nodes_only);
20713
0
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
20714
0
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
20715
0
        SameLine();
20716
0
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
20717
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
20718
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
20719
0
                if (!root_nodes_only || node->IsRootNode())
20720
0
                    DebugNodeDockNode(node, "Node");
20721
0
        TreePop();
20722
0
    }
20723
0
#endif // #ifdef IMGUI_HAS_DOCK
20724
20725
    // Settings
20726
0
    if (TreeNode("Settings"))
20727
0
    {
20728
0
        if (SmallButton("Clear"))
20729
0
            ClearIniSettings();
20730
0
        SameLine();
20731
0
        if (SmallButton("Save to memory"))
20732
0
            SaveIniSettingsToMemory();
20733
0
        SameLine();
20734
0
        if (SmallButton("Save to disk"))
20735
0
            SaveIniSettingsToDisk(g.IO.IniFilename);
20736
0
        SameLine();
20737
0
        if (g.IO.IniFilename)
20738
0
            Text("\"%s\"", g.IO.IniFilename);
20739
0
        else
20740
0
            TextUnformatted("<NULL>");
20741
0
        Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
20742
0
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
20743
0
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
20744
0
        {
20745
0
            for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
20746
0
                BulletText("\"%s\"", handler.TypeName);
20747
0
            TreePop();
20748
0
        }
20749
0
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
20750
0
        {
20751
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20752
0
                DebugNodeWindowSettings(settings);
20753
0
            TreePop();
20754
0
        }
20755
20756
0
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
20757
0
        {
20758
0
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
20759
0
                DebugNodeTableSettings(settings);
20760
0
            TreePop();
20761
0
        }
20762
20763
0
#ifdef IMGUI_HAS_DOCK
20764
0
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
20765
0
        {
20766
0
            ImGuiDockContext* dc = &g.DockContext;
20767
0
            Text("In SettingsWindows:");
20768
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20769
0
                if (settings->DockId != 0)
20770
0
                    BulletText("Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder);
20771
0
            Text("In SettingsNodes:");
20772
0
            for (int n = 0; n < dc->NodesSettings.Size; n++)
20773
0
            {
20774
0
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
20775
0
                const char* selected_tab_name = NULL;
20776
0
                if (settings->SelectedTabId)
20777
0
                {
20778
0
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
20779
0
                        selected_tab_name = window->Name;
20780
0
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
20781
0
                        selected_tab_name = window_settings->GetName();
20782
0
                }
20783
0
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
20784
0
            }
20785
0
            TreePop();
20786
0
        }
20787
0
#endif // #ifdef IMGUI_HAS_DOCK
20788
20789
0
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
20790
0
        {
20791
0
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
20792
0
            TreePop();
20793
0
        }
20794
0
        TreePop();
20795
0
    }
20796
20797
    // Settings
20798
0
    if (TreeNode("Memory allocations"))
20799
0
    {
20800
0
        ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
20801
0
        Text("%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
20802
0
        if (SmallButton("GC now")) { g.GcCompactAll = true; }
20803
0
        Text("Recent frames with allocations:");
20804
0
        int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf);
20805
0
        for (int n = buf_size - 1; n >= 0; n--)
20806
0
        {
20807
0
            ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
20808
0
            BulletText("Frame %06d: %+3d ( %2d malloc, %2d free )%s", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount, (n == 0) ? " (most recent)" : "");
20809
0
        }
20810
0
        TreePop();
20811
0
    }
20812
20813
0
    if (TreeNode("Inputs"))
20814
0
    {
20815
0
        Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
20816
0
        {
20817
            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
20818
            // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
20819
0
            Indent();
20820
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
20821
0
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
20822
#else
20823
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key >= 0 && key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
20824
            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
20825
#endif
20826
0
            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
20827
0
            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
20828
0
            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
20829
0
            Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
20830
0
            Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
20831
0
            DebugRenderKeyboardPreview(GetWindowDrawList());
20832
0
            Unindent();
20833
0
        }
20834
20835
0
        Text("MOUSE STATE");
20836
0
        {
20837
0
            Indent();
20838
0
            if (IsMousePosValid())
20839
0
                Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
20840
0
            else
20841
0
                Text("Mouse pos: <INVALID>");
20842
0
            Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
20843
0
            int count = IM_ARRAYSIZE(io.MouseDown);
20844
0
            Text("Mouse down:");     for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
20845
0
            Text("Mouse clicked:");  for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
20846
0
            Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
20847
0
            Text("Mouse wheel: %.1f", io.MouseWheel);
20848
0
            Text("MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
20849
0
            Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
20850
0
            Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
20851
0
            Unindent();
20852
0
        }
20853
20854
0
        Text("MOUSE WHEELING");
20855
0
        {
20856
0
            Indent();
20857
0
            Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
20858
0
            Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
20859
0
            Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
20860
0
            Unindent();
20861
0
        }
20862
20863
0
        Text("KEY OWNERS");
20864
0
        {
20865
0
            Indent();
20866
0
            if (BeginChild("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
20867
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20868
0
                {
20869
0
                    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
20870
0
                    if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
20871
0
                        continue;
20872
0
                    Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
20873
0
                        owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
20874
0
                    DebugLocateItemOnHover(owner_data->OwnerCurr);
20875
0
                }
20876
0
            EndChild();
20877
0
            Unindent();
20878
0
        }
20879
0
        Text("SHORTCUT ROUTING");
20880
0
        SameLine();
20881
0
        MetricsHelpMarker("Declared shortcut routes automatically set key owner when mods matches.");
20882
0
        {
20883
0
            Indent();
20884
0
            if (BeginChild("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
20885
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20886
0
                {
20887
0
                    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
20888
0
                    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
20889
0
                    {
20890
0
                        ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
20891
0
                        ImGuiKeyChord key_chord = key | routing_data->Mods;
20892
0
                        Text("%s: 0x%08X (scored %d)", GetKeyChordName(key_chord), routing_data->RoutingCurr, routing_data->RoutingCurrScore);
20893
0
                        DebugLocateItemOnHover(routing_data->RoutingCurr);
20894
0
                        if (g.IO.ConfigDebugIsDebuggerPresent)
20895
0
                        {
20896
0
                            SameLine();
20897
0
                            if (DebugBreakButton("**DebugBreak**", "in SetShortcutRouting() for this KeyChord"))
20898
0
                                g.DebugBreakInShortcutRouting = key_chord;
20899
0
                        }
20900
0
                        idx = routing_data->NextEntryIndex;
20901
0
                    }
20902
0
                }
20903
0
            EndChild();
20904
0
            Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20905
0
            Unindent();
20906
0
        }
20907
0
        TreePop();
20908
0
    }
20909
20910
0
    if (TreeNode("Internal state"))
20911
0
    {
20912
0
        Text("WINDOWING");
20913
0
        Indent();
20914
0
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
20915
0
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
20916
0
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
20917
0
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
20918
0
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
20919
0
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20920
0
        Unindent();
20921
20922
0
        Text("ITEMS");
20923
0
        Indent();
20924
0
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
20925
0
        DebugLocateItemOnHover(g.ActiveId);
20926
0
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
20927
0
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20928
0
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
20929
0
        Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
20930
0
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
20931
0
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
20932
0
        Unindent();
20933
20934
0
        Text("NAV,FOCUS");
20935
0
        Indent();
20936
0
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
20937
0
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
20938
0
        DebugLocateItemOnHover(g.NavId);
20939
0
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
20940
0
        Text("NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
20941
0
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
20942
0
        Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
20943
0
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
20944
0
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
20945
0
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
20946
0
        Text("NavFocusRoute[] = ");
20947
0
        for (int path_n = g.NavFocusRoute.Size - 1; path_n >= 0; path_n--)
20948
0
        {
20949
0
            const ImGuiFocusScopeData& focus_scope = g.NavFocusRoute[path_n];
20950
0
            SameLine(0.0f, 0.0f);
20951
0
            Text("0x%08X/", focus_scope.ID);
20952
0
            SetItemTooltip("In window \"%s\"", FindWindowByID(focus_scope.WindowID)->Name);
20953
0
        }
20954
0
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
20955
0
        Unindent();
20956
20957
0
        TreePop();
20958
0
    }
20959
20960
    // Overlay: Display windows Rectangles and Begin Order
20961
0
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
20962
0
    {
20963
0
        for (ImGuiWindow* window : g.Windows)
20964
0
        {
20965
0
            if (!window->WasActive)
20966
0
                continue;
20967
0
            ImDrawList* draw_list = GetForegroundDrawList(window);
20968
0
            if (cfg->ShowWindowsRects)
20969
0
            {
20970
0
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
20971
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20972
0
            }
20973
0
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
20974
0
            {
20975
0
                char buf[32];
20976
0
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
20977
0
                float font_size = GetFontSize();
20978
0
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
20979
0
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
20980
0
            }
20981
0
        }
20982
0
    }
20983
20984
    // Overlay: Display Tables Rectangles
20985
0
    if (cfg->ShowTablesRects)
20986
0
    {
20987
0
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20988
0
        {
20989
0
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
20990
0
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
20991
0
                continue;
20992
0
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
20993
0
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
20994
0
            {
20995
0
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20996
0
                {
20997
0
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
20998
0
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
20999
0
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
21000
0
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
21001
0
                }
21002
0
            }
21003
0
            else
21004
0
            {
21005
0
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
21006
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
21007
0
            }
21008
0
        }
21009
0
    }
21010
21011
0
#ifdef IMGUI_HAS_DOCK
21012
    // Overlay: Display Docking info
21013
0
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
21014
0
    {
21015
0
        char buf[64] = "";
21016
0
        char* p = buf;
21017
0
        ImGuiDockNode* node = g.DebugHoveredDockNode;
21018
0
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
21019
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
21020
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
21021
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
21022
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
21023
0
        int depth = DockNodeGetDepth(node);
21024
0
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
21025
0
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
21026
0
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
21027
0
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
21028
0
    }
21029
0
#endif // #ifdef IMGUI_HAS_DOCK
21030
21031
0
    End();
21032
0
}
21033
21034
void ImGui::DebugBreakClearData()
21035
0
{
21036
    // Those fields are scattered in their respective subsystem to stay in hot-data locations
21037
0
    ImGuiContext& g = *GImGui;
21038
0
    g.DebugBreakInWindow = 0;
21039
0
    g.DebugBreakInTable = 0;
21040
0
    g.DebugBreakInShortcutRouting = ImGuiKey_None;
21041
0
}
21042
21043
void ImGui::DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location)
21044
0
{
21045
0
    if (!BeginItemTooltip())
21046
0
        return;
21047
0
    Text("To call IM_DEBUG_BREAK() %s:", description_of_location);
21048
0
    Separator();
21049
0
    TextUnformatted(keyboard_only ? "- Press 'Pause/Break' on keyboard." : "- Press 'Pause/Break' on keyboard.\n- or Click (may alter focus/active id).\n- or navigate using keyboard and press space.");
21050
0
    Separator();
21051
0
    TextUnformatted("Choose one way that doesn't interfere with what you are trying to debug!\nYou need a debugger attached or this will crash!");
21052
0
    EndTooltip();
21053
0
}
21054
21055
// Special button that doesn't take focus, doesn't take input owner, and can be activated without a click etc.
21056
// In order to reduce interferences with the contents we are trying to debug into.
21057
bool ImGui::DebugBreakButton(const char* label, const char* description_of_location)
21058
0
{
21059
0
    ImGuiWindow* window = GetCurrentWindow();
21060
0
    if (window->SkipItems)
21061
0
        return false;
21062
21063
0
    ImGuiContext& g = *GImGui;
21064
0
    const ImGuiID id = window->GetID(label);
21065
0
    const ImVec2 label_size = CalcTextSize(label, NULL, true);
21066
0
    ImVec2 pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrLineTextBaseOffset);
21067
0
    ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x * 2.0f, label_size.y);
21068
21069
0
    const ImRect bb(pos, pos + size);
21070
0
    ItemSize(size, 0.0f);
21071
0
    if (!ItemAdd(bb, id))
21072
0
        return false;
21073
21074
    // WE DO NOT USE ButtonEx() or ButtonBehavior() in order to reduce our side-effects.
21075
0
    bool hovered = ItemHoverable(bb, id, g.CurrentItemFlags);
21076
0
    bool pressed = hovered && (IsKeyChordPressed(g.DebugBreakKeyChord) || IsMouseClicked(0) || g.NavActivateId == id);
21077
0
    DebugBreakButtonTooltip(false, description_of_location);
21078
21079
0
    ImVec4 col4f = GetStyleColorVec4(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
21080
0
    ImVec4 hsv;
21081
0
    ColorConvertRGBtoHSV(col4f.x, col4f.y, col4f.z, hsv.x, hsv.y, hsv.z);
21082
0
    ColorConvertHSVtoRGB(hsv.x + 0.20f, hsv.y, hsv.z, col4f.x, col4f.y, col4f.z);
21083
21084
0
    RenderNavHighlight(bb, id);
21085
0
    RenderFrame(bb.Min, bb.Max, GetColorU32(col4f), true, g.Style.FrameRounding);
21086
0
    RenderTextClipped(bb.Min, bb.Max, label, NULL, &label_size, g.Style.ButtonTextAlign, &bb);
21087
21088
0
    IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
21089
0
    return pressed;
21090
0
}
21091
21092
// [DEBUG] Display contents of Columns
21093
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
21094
0
{
21095
0
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
21096
0
        return;
21097
0
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
21098
0
    for (ImGuiOldColumnData& column : columns->Columns)
21099
0
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(&column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, column.OffsetNorm));
21100
0
    TreePop();
21101
0
}
21102
21103
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
21104
0
{
21105
0
    using namespace ImGui;
21106
0
    PushID(label);
21107
0
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
21108
0
    Text("%s:", label);
21109
0
    if (!enabled)
21110
0
        BeginDisabled();
21111
0
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
21112
0
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
21113
0
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
21114
0
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
21115
0
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
21116
0
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
21117
0
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
21118
0
    CheckboxFlags("DockedWindowsInFocusRoute", p_flags, ImGuiDockNodeFlags_DockedWindowsInFocusRoute);
21119
0
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking); // Multiple flags
21120
0
    CheckboxFlags("NoDockingSplit", p_flags, ImGuiDockNodeFlags_NoDockingSplit);
21121
0
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
21122
0
    CheckboxFlags("NoDockingOver", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
21123
0
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
21124
0
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
21125
0
    CheckboxFlags("NoUndocking", p_flags, ImGuiDockNodeFlags_NoUndocking);
21126
0
    if (!enabled)
21127
0
        EndDisabled();
21128
0
    PopStyleVar();
21129
0
    PopID();
21130
0
}
21131
21132
// [DEBUG] Display contents of ImDockNode
21133
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
21134
0
{
21135
0
    ImGuiContext& g = *GImGui;
21136
0
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
21137
0
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
21138
0
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
21139
0
    bool open;
21140
0
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
21141
0
    if (node->Windows.Size > 0)
21142
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
21143
0
    else
21144
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
21145
0
    if (!is_alive) { PopStyleColor(); }
21146
0
    if (is_active && IsItemHovered())
21147
0
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
21148
0
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
21149
0
    if (open)
21150
0
    {
21151
0
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
21152
0
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
21153
0
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
21154
0
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
21155
0
        DebugNodeWindow(node->HostWindow, "HostWindow");
21156
0
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
21157
0
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
21158
0
        BulletText("Misc:%s%s%s%s%s%s%s",
21159
0
            node->IsDockSpace() ? " IsDockSpace" : "",
21160
0
            node->IsCentralNode() ? " IsCentralNode" : "",
21161
0
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
21162
0
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
21163
0
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
21164
0
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
21165
0
        {
21166
0
            if (BeginTable("flags", 4))
21167
0
            {
21168
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
21169
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
21170
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
21171
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
21172
0
                EndTable();
21173
0
            }
21174
0
            TreePop();
21175
0
        }
21176
0
        if (node->ParentNode)
21177
0
            DebugNodeDockNode(node->ParentNode, "ParentNode");
21178
0
        if (node->ChildNodes[0])
21179
0
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
21180
0
        if (node->ChildNodes[1])
21181
0
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
21182
0
        if (node->TabBar)
21183
0
            DebugNodeTabBar(node->TabBar, "TabBar");
21184
0
        DebugNodeWindowsList(&node->Windows, "Windows");
21185
21186
0
        TreePop();
21187
0
    }
21188
0
}
21189
21190
static void FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
21191
0
{
21192
0
    union { void* ptr; int integer; } tex_id_opaque;
21193
0
    memcpy(&tex_id_opaque, &tex_id, ImMin(sizeof(void*), sizeof(tex_id)));
21194
0
    if (sizeof(tex_id) >= sizeof(void*))
21195
0
        ImFormatString(buf, buf_size, "0x%p", tex_id_opaque.ptr);
21196
0
    else
21197
0
        ImFormatString(buf, buf_size, "0x%04X", tex_id_opaque.integer);
21198
0
}
21199
21200
// [DEBUG] Display contents of ImDrawList
21201
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
21202
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
21203
0
{
21204
0
    ImGuiContext& g = *GImGui;
21205
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
21206
0
    int cmd_count = draw_list->CmdBuffer.Size;
21207
0
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
21208
0
        cmd_count--;
21209
0
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
21210
0
    if (draw_list == GetWindowDrawList())
21211
0
    {
21212
0
        SameLine();
21213
0
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
21214
0
        if (node_open)
21215
0
            TreePop();
21216
0
        return;
21217
0
    }
21218
21219
0
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
21220
0
    if (window && IsItemHovered() && fg_draw_list)
21221
0
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
21222
0
    if (!node_open)
21223
0
        return;
21224
21225
0
    if (window && !window->WasActive)
21226
0
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
21227
21228
0
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
21229
0
    {
21230
0
        if (pcmd->UserCallback)
21231
0
        {
21232
0
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
21233
0
            continue;
21234
0
        }
21235
21236
0
        char texid_desc[20];
21237
0
        FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TextureId);
21238
0
        char buf[300];
21239
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
21240
0
            pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
21241
0
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
21242
0
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
21243
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
21244
0
        if (!pcmd_node_open)
21245
0
            continue;
21246
21247
        // Calculate approximate coverage area (touched pixel count)
21248
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
21249
0
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
21250
0
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
21251
0
        float total_area = 0.0f;
21252
0
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
21253
0
        {
21254
0
            ImVec2 triangle[3];
21255
0
            for (int n = 0; n < 3; n++, idx_n++)
21256
0
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
21257
0
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
21258
0
        }
21259
21260
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
21261
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
21262
0
        Selectable(buf);
21263
0
        if (IsItemHovered() && fg_draw_list)
21264
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
21265
21266
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
21267
0
        ImGuiListClipper clipper;
21268
0
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
21269
0
        while (clipper.Step())
21270
0
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
21271
0
            {
21272
0
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
21273
0
                ImVec2 triangle[3];
21274
0
                for (int n = 0; n < 3; n++, idx_i++)
21275
0
                {
21276
0
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
21277
0
                    triangle[n] = v.pos;
21278
0
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
21279
0
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
21280
0
                }
21281
21282
0
                Selectable(buf, false);
21283
0
                if (fg_draw_list && IsItemHovered())
21284
0
                {
21285
0
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
21286
0
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
21287
0
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
21288
0
                    fg_draw_list->Flags = backup_flags;
21289
0
                }
21290
0
            }
21291
0
        TreePop();
21292
0
    }
21293
0
    TreePop();
21294
0
}
21295
21296
// [DEBUG] Display mesh/aabb of a ImDrawCmd
21297
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
21298
0
{
21299
0
    IM_ASSERT(show_mesh || show_aabb);
21300
21301
    // Draw wire-frame version of all triangles
21302
0
    ImRect clip_rect = draw_cmd->ClipRect;
21303
0
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
21304
0
    ImDrawListFlags backup_flags = out_draw_list->Flags;
21305
0
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
21306
0
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
21307
0
    {
21308
0
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
21309
0
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
21310
21311
0
        ImVec2 triangle[3];
21312
0
        for (int n = 0; n < 3; n++, idx_n++)
21313
0
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
21314
0
        if (show_mesh)
21315
0
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
21316
0
    }
21317
    // Draw bounding boxes
21318
0
    if (show_aabb)
21319
0
    {
21320
0
        out_draw_list->AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
21321
0
        out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
21322
0
    }
21323
0
    out_draw_list->Flags = backup_flags;
21324
0
}
21325
21326
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
21327
void ImGui::DebugNodeFont(ImFont* font)
21328
0
{
21329
0
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
21330
0
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
21331
0
    SameLine();
21332
0
    if (SmallButton("Set as default"))
21333
0
        GetIO().FontDefault = font;
21334
0
    if (!opened)
21335
0
        return;
21336
21337
    // Display preview text
21338
0
    PushFont(font);
21339
0
    Text("The quick brown fox jumps over the lazy dog");
21340
0
    PopFont();
21341
21342
    // Display details
21343
0
    SetNextItemWidth(GetFontSize() * 8);
21344
0
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
21345
0
    SameLine(); MetricsHelpMarker(
21346
0
        "Note that the default embedded font is NOT meant to be scaled.\n\n"
21347
0
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
21348
0
        "You may oversample them to get some flexibility with scaling. "
21349
0
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
21350
0
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
21351
0
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
21352
0
    char c_str[5];
21353
0
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
21354
0
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
21355
0
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
21356
0
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
21357
0
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
21358
0
        if (font->ConfigData)
21359
0
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
21360
0
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
21361
0
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
21362
21363
    // Display all glyphs of the fonts in separate pages of 256 characters
21364
0
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
21365
0
    {
21366
0
        ImDrawList* draw_list = GetWindowDrawList();
21367
0
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
21368
0
        const float cell_size = font->FontSize * 1;
21369
0
        const float cell_spacing = GetStyle().ItemSpacing.y;
21370
0
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
21371
0
        {
21372
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
21373
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
21374
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
21375
0
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
21376
0
            {
21377
0
                base += 4096 - 256;
21378
0
                continue;
21379
0
            }
21380
21381
0
            int count = 0;
21382
0
            for (unsigned int n = 0; n < 256; n++)
21383
0
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
21384
0
                    count++;
21385
0
            if (count <= 0)
21386
0
                continue;
21387
0
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
21388
0
                continue;
21389
21390
            // Draw a 16x16 grid of glyphs
21391
0
            ImVec2 base_pos = GetCursorScreenPos();
21392
0
            for (unsigned int n = 0; n < 256; n++)
21393
0
            {
21394
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
21395
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
21396
0
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
21397
0
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
21398
0
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
21399
0
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
21400
0
                if (!glyph)
21401
0
                    continue;
21402
0
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
21403
0
                if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
21404
0
                {
21405
0
                    DebugNodeFontGlyph(font, glyph);
21406
0
                    EndTooltip();
21407
0
                }
21408
0
            }
21409
0
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
21410
0
            TreePop();
21411
0
        }
21412
0
        TreePop();
21413
0
    }
21414
0
    TreePop();
21415
0
}
21416
21417
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
21418
0
{
21419
0
    Text("Codepoint: U+%04X", glyph->Codepoint);
21420
0
    Separator();
21421
0
    Text("Visible: %d", glyph->Visible);
21422
0
    Text("AdvanceX: %.1f", glyph->AdvanceX);
21423
0
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
21424
0
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
21425
0
}
21426
21427
// [DEBUG] Display contents of ImGuiStorage
21428
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
21429
0
{
21430
0
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
21431
0
        return;
21432
0
    for (const ImGuiStoragePair& p : storage->Data)
21433
0
    {
21434
0
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
21435
0
        DebugLocateItemOnHover(p.key);
21436
0
    }
21437
0
    TreePop();
21438
0
}
21439
21440
// [DEBUG] Display contents of ImGuiTabBar
21441
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
21442
0
{
21443
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
21444
0
    char buf[256];
21445
0
    char* p = buf;
21446
0
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
21447
0
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
21448
0
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s  {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
21449
0
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
21450
0
    {
21451
0
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
21452
0
        p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
21453
0
    }
21454
0
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
21455
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
21456
0
    bool open = TreeNode(label, "%s", buf);
21457
0
    if (!is_active) { PopStyleColor(); }
21458
0
    if (is_active && IsItemHovered())
21459
0
    {
21460
0
        ImDrawList* draw_list = GetForegroundDrawList();
21461
0
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
21462
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
21463
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
21464
0
    }
21465
0
    if (open)
21466
0
    {
21467
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
21468
0
        {
21469
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
21470
0
            PushID(tab);
21471
0
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
21472
0
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
21473
0
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
21474
0
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
21475
0
            PopID();
21476
0
        }
21477
0
        TreePop();
21478
0
    }
21479
0
}
21480
21481
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
21482
0
{
21483
0
    ImGuiContext& g = *GImGui;
21484
0
    SetNextItemOpen(true, ImGuiCond_Once);
21485
0
    bool open = TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A");
21486
0
    if (IsItemHovered())
21487
0
        g.DebugMetricsConfig.HighlightViewportID = viewport->ID;
21488
0
    if (open)
21489
0
    {
21490
0
        ImGuiWindowFlags flags = viewport->Flags;
21491
0
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
21492
0
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
21493
0
            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
21494
0
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
21495
0
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
21496
0
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
21497
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
21498
0
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
21499
0
            (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
21500
0
            (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
21501
0
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
21502
0
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
21503
0
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
21504
0
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
21505
0
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
21506
0
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
21507
0
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
21508
0
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
21509
0
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
21510
0
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
21511
0
        for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
21512
0
            DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
21513
0
        TreePop();
21514
0
    }
21515
0
}
21516
21517
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
21518
0
{
21519
0
    if (window == NULL)
21520
0
    {
21521
0
        BulletText("%s: NULL", label);
21522
0
        return;
21523
0
    }
21524
21525
0
    ImGuiContext& g = *GImGui;
21526
0
    const bool is_active = window->WasActive;
21527
0
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
21528
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
21529
0
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
21530
0
    if (!is_active) { PopStyleColor(); }
21531
0
    if (IsItemHovered() && is_active)
21532
0
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
21533
0
    if (!open)
21534
0
        return;
21535
21536
0
    if (window->MemoryCompacted)
21537
0
        TextDisabled("Note: some memory buffers have been compacted/freed.");
21538
21539
0
    if (g.IO.ConfigDebugIsDebuggerPresent && DebugBreakButton("**DebugBreak**", "in Begin()"))
21540
0
        g.DebugBreakInWindow = window->ID;
21541
21542
0
    ImGuiWindowFlags flags = window->Flags;
21543
0
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
21544
0
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
21545
0
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
21546
0
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
21547
0
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
21548
0
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
21549
0
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
21550
0
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
21551
0
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
21552
0
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
21553
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
21554
0
    {
21555
0
        ImRect r = window->NavRectRel[layer];
21556
0
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
21557
0
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
21558
0
        else
21559
0
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
21560
0
        DebugLocateItemOnHover(window->NavLastIds[layer]);
21561
0
    }
21562
0
    const ImVec2* pr = window->NavPreferredScoringPosRel;
21563
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
21564
0
        BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
21565
0
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
21566
21567
0
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
21568
0
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
21569
0
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
21570
0
    if (window->DockNode || window->DockNodeAsHost)
21571
0
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
21572
21573
0
    if (window->RootWindow != window)               { DebugNodeWindow(window->RootWindow, "RootWindow"); }
21574
0
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
21575
0
    if (window->ParentWindow != NULL)               { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
21576
0
    if (window->ParentWindowForFocusRoute != NULL)  { DebugNodeWindow(window->ParentWindowForFocusRoute, "ParentWindowForFocusRoute"); }
21577
0
    if (window->DC.ChildWindows.Size > 0)           { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
21578
0
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
21579
0
    {
21580
0
        for (ImGuiOldColumns& columns : window->ColumnsStorage)
21581
0
            DebugNodeColumns(&columns);
21582
0
        TreePop();
21583
0
    }
21584
0
    DebugNodeStorage(&window->StateStorage, "Storage");
21585
0
    TreePop();
21586
0
}
21587
21588
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
21589
0
{
21590
0
    if (settings->WantDelete)
21591
0
        BeginDisabled();
21592
0
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
21593
0
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
21594
0
    if (settings->WantDelete)
21595
0
        EndDisabled();
21596
0
}
21597
21598
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
21599
0
{
21600
0
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
21601
0
        return;
21602
0
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
21603
0
    {
21604
0
        PushID((*windows)[i]);
21605
0
        DebugNodeWindow((*windows)[i], "Window");
21606
0
        PopID();
21607
0
    }
21608
0
    TreePop();
21609
0
}
21610
21611
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
21612
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
21613
0
{
21614
0
    for (int i = 0; i < windows_size; i++)
21615
0
    {
21616
0
        ImGuiWindow* window = windows[i];
21617
0
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
21618
0
            continue;
21619
0
        char buf[20];
21620
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
21621
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
21622
0
        DebugNodeWindow(window, buf);
21623
0
        Indent();
21624
0
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
21625
0
        Unindent();
21626
0
    }
21627
0
}
21628
21629
//-----------------------------------------------------------------------------
21630
// [SECTION] DEBUG LOG WINDOW
21631
//-----------------------------------------------------------------------------
21632
21633
void ImGui::DebugLog(const char* fmt, ...)
21634
0
{
21635
0
    va_list args;
21636
0
    va_start(args, fmt);
21637
0
    DebugLogV(fmt, args);
21638
0
    va_end(args);
21639
0
}
21640
21641
void ImGui::DebugLogV(const char* fmt, va_list args)
21642
0
{
21643
0
    ImGuiContext& g = *GImGui;
21644
0
    const int old_size = g.DebugLogBuf.size();
21645
0
    if (g.ContextName[0] != 0)
21646
0
        g.DebugLogBuf.appendf("[%s] [%05d] ", g.ContextName, g.FrameCount);
21647
0
    else
21648
0
        g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
21649
0
    g.DebugLogBuf.appendfv(fmt, args);
21650
0
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
21651
0
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
21652
0
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
21653
#ifdef IMGUI_ENABLE_TEST_ENGINE
21654
    // IMGUI_TEST_ENGINE_LOG() adds a trailing \n automatically
21655
    const int new_size = g.DebugLogBuf.size();
21656
    const bool trailing_carriage_return = (g.DebugLogBuf[new_size - 1] == '\n');
21657
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
21658
        IMGUI_TEST_ENGINE_LOG("%.*s", new_size - old_size - (trailing_carriage_return ? 1 : 0), g.DebugLogBuf.begin() + old_size);
21659
#endif
21660
0
}
21661
21662
// FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout.
21663
static void SameLineOrWrap(const ImVec2& size)
21664
0
{
21665
0
    ImGuiContext& g = *GImGui;
21666
0
    ImGuiWindow* window = g.CurrentWindow;
21667
0
    ImVec2 pos(window->DC.CursorPosPrevLine.x + g.Style.ItemSpacing.x, window->DC.CursorPosPrevLine.y);
21668
0
    if (window->ClipRect.Contains(ImRect(pos, pos + size)))
21669
0
        ImGui::SameLine();
21670
0
}
21671
21672
static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags)
21673
0
{
21674
0
    ImGuiContext& g = *GImGui;
21675
0
    ImVec2 size(ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui::CalcTextSize(name).x, ImGui::GetFrameHeight());
21676
0
    SameLineOrWrap(size); // FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout.
21677
0
    if (ImGui::CheckboxFlags(name, &g.DebugLogFlags, flags) && g.IO.KeyShift && (g.DebugLogFlags & flags) != 0)
21678
0
    {
21679
0
        g.DebugLogAutoDisableFrames = 2;
21680
0
        g.DebugLogAutoDisableFlags |= flags;
21681
0
    }
21682
0
    ImGui::SetItemTooltip("Hold SHIFT when clicking to enable for 2 frames only (useful for spammy log entries)");
21683
0
}
21684
21685
void ImGui::ShowDebugLogWindow(bool* p_open)
21686
0
{
21687
0
    ImGuiContext& g = *GImGui;
21688
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
21689
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
21690
0
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
21691
0
    {
21692
0
        End();
21693
0
        return;
21694
0
    }
21695
21696
0
    ImGuiDebugLogFlags all_enable_flags = ImGuiDebugLogFlags_EventMask_ & ~ImGuiDebugLogFlags_EventInputRouting;
21697
0
    CheckboxFlags("All", &g.DebugLogFlags, all_enable_flags);
21698
0
    SetItemTooltip("(except InputRouting which is spammy)");
21699
21700
0
    ShowDebugLogFlag("ActiveId", ImGuiDebugLogFlags_EventActiveId);
21701
0
    ShowDebugLogFlag("Clipper", ImGuiDebugLogFlags_EventClipper);
21702
0
    ShowDebugLogFlag("Docking", ImGuiDebugLogFlags_EventDocking);
21703
0
    ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus);
21704
0
    ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO);
21705
0
    ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav);
21706
0
    ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup);
21707
0
    ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection);
21708
0
    ShowDebugLogFlag("Viewport", ImGuiDebugLogFlags_EventViewport);
21709
0
    ShowDebugLogFlag("InputRouting", ImGuiDebugLogFlags_EventInputRouting);
21710
21711
0
    if (SmallButton("Clear"))
21712
0
    {
21713
0
        g.DebugLogBuf.clear();
21714
0
        g.DebugLogIndex.clear();
21715
0
    }
21716
0
    SameLine();
21717
0
    if (SmallButton("Copy"))
21718
0
        SetClipboardText(g.DebugLogBuf.c_str());
21719
0
    SameLine();
21720
0
    if (SmallButton("Configure Outputs.."))
21721
0
        OpenPopup("Outputs");
21722
0
    if (BeginPopup("Outputs"))
21723
0
    {
21724
0
        CheckboxFlags("OutputToTTY", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTTY);
21725
0
#ifndef IMGUI_ENABLE_TEST_ENGINE
21726
0
        BeginDisabled();
21727
0
#endif
21728
0
        CheckboxFlags("OutputToTestEngine", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTestEngine);
21729
0
#ifndef IMGUI_ENABLE_TEST_ENGINE
21730
0
        EndDisabled();
21731
0
#endif
21732
0
        EndPopup();
21733
0
    }
21734
21735
0
    BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Border, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
21736
21737
0
    const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags;
21738
0
    g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
21739
21740
0
    ImGuiListClipper clipper;
21741
0
    clipper.Begin(g.DebugLogIndex.size());
21742
0
    while (clipper.Step())
21743
0
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
21744
0
            DebugTextUnformattedWithLocateItem(g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no), g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no));
21745
0
    g.DebugLogFlags = backup_log_flags;
21746
0
    if (GetScrollY() >= GetScrollMaxY())
21747
0
        SetScrollHereY(1.0f);
21748
0
    EndChild();
21749
21750
0
    End();
21751
0
}
21752
21753
// Display line, search for 0xXXXXXXXX identifiers and call DebugLocateItemOnHover() when hovered.
21754
void ImGui::DebugTextUnformattedWithLocateItem(const char* line_begin, const char* line_end)
21755
0
{
21756
0
    TextUnformatted(line_begin, line_end);
21757
0
    if (!IsItemHovered())
21758
0
        return;
21759
0
    ImGuiContext& g = *GImGui;
21760
0
    ImRect text_rect = g.LastItemData.Rect;
21761
0
    for (const char* p = line_begin; p <= line_end - 10; p++)
21762
0
    {
21763
0
        ImGuiID id = 0;
21764
0
        if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1)
21765
0
            continue;
21766
0
        ImVec2 p0 = CalcTextSize(line_begin, p);
21767
0
        ImVec2 p1 = CalcTextSize(p, p + 10);
21768
0
        g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
21769
0
        if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
21770
0
            DebugLocateItemOnHover(id);
21771
0
        p += 10;
21772
0
    }
21773
0
}
21774
21775
//-----------------------------------------------------------------------------
21776
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
21777
//-----------------------------------------------------------------------------
21778
21779
// Draw a small cross at current CursorPos in current window's DrawList
21780
void ImGui::DebugDrawCursorPos(ImU32 col)
21781
0
{
21782
0
    ImGuiContext& g = *GImGui;
21783
0
    ImGuiWindow* window = g.CurrentWindow;
21784
0
    ImVec2 pos = window->DC.CursorPos;
21785
0
    window->DrawList->AddLine(ImVec2(pos.x, pos.y - 3.0f), ImVec2(pos.x, pos.y + 4.0f), col, 1.0f);
21786
0
    window->DrawList->AddLine(ImVec2(pos.x - 3.0f, pos.y), ImVec2(pos.x + 4.0f, pos.y), col, 1.0f);
21787
0
}
21788
21789
// Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
21790
void ImGui::DebugDrawLineExtents(ImU32 col)
21791
0
{
21792
0
    ImGuiContext& g = *GImGui;
21793
0
    ImGuiWindow* window = g.CurrentWindow;
21794
0
    float curr_x = window->DC.CursorPos.x;
21795
0
    float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
21796
0
    float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
21797
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y1), ImVec2(curr_x + 5.0f, line_y1), col, 1.0f);
21798
0
    window->DrawList->AddLine(ImVec2(curr_x - 0.5f, line_y1), ImVec2(curr_x - 0.5f, line_y2), col, 1.0f);
21799
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y2), ImVec2(curr_x + 5.0f, line_y2), col, 1.0f);
21800
0
}
21801
21802
// Draw last item rect in ForegroundDrawList (so it is always visible)
21803
void ImGui::DebugDrawItemRect(ImU32 col)
21804
0
{
21805
0
    ImGuiContext& g = *GImGui;
21806
0
    ImGuiWindow* window = g.CurrentWindow;
21807
0
    GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col);
21808
0
}
21809
21810
// [DEBUG] Locate item position/rectangle given an ID.
21811
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
21812
21813
void ImGui::DebugLocateItem(ImGuiID target_id)
21814
0
{
21815
0
    ImGuiContext& g = *GImGui;
21816
0
    g.DebugLocateId = target_id;
21817
0
    g.DebugLocateFrames = 2;
21818
0
    g.DebugBreakInLocateId = false;
21819
0
}
21820
21821
// FIXME: Doesn't work over through a modal window, because they clear HoveredWindow.
21822
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
21823
0
{
21824
0
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
21825
0
        return;
21826
0
    ImGuiContext& g = *GImGui;
21827
0
    DebugLocateItem(target_id);
21828
0
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
21829
21830
    // Can't easily use a context menu here because it will mess with focus, active id etc.
21831
0
    if (g.IO.ConfigDebugIsDebuggerPresent && g.MouseStationaryTimer > 1.0f)
21832
0
    {
21833
0
        DebugBreakButtonTooltip(false, "in ItemAdd()");
21834
0
        if (IsKeyChordPressed(g.DebugBreakKeyChord))
21835
0
            g.DebugBreakInLocateId = true;
21836
0
    }
21837
0
}
21838
21839
void ImGui::DebugLocateItemResolveWithLastItem()
21840
0
{
21841
0
    ImGuiContext& g = *GImGui;
21842
21843
    // [DEBUG] Debug break requested by user
21844
0
    if (g.DebugBreakInLocateId)
21845
0
        IM_DEBUG_BREAK();
21846
21847
0
    ImGuiLastItemData item_data = g.LastItemData;
21848
0
    g.DebugLocateId = 0;
21849
0
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
21850
0
    ImRect r = item_data.Rect;
21851
0
    r.Expand(3.0f);
21852
0
    ImVec2 p1 = g.IO.MousePos;
21853
0
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
21854
0
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
21855
0
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
21856
0
}
21857
21858
void ImGui::DebugStartItemPicker()
21859
0
{
21860
0
    ImGuiContext& g = *GImGui;
21861
0
    g.DebugItemPickerActive = true;
21862
0
}
21863
21864
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
21865
void ImGui::UpdateDebugToolItemPicker()
21866
58.4k
{
21867
58.4k
    ImGuiContext& g = *GImGui;
21868
58.4k
    g.DebugItemPickerBreakId = 0;
21869
58.4k
    if (!g.DebugItemPickerActive)
21870
58.4k
        return;
21871
21872
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
21873
0
    SetMouseCursor(ImGuiMouseCursor_Hand);
21874
0
    if (IsKeyPressed(ImGuiKey_Escape))
21875
0
        g.DebugItemPickerActive = false;
21876
0
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
21877
0
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
21878
0
    {
21879
0
        g.DebugItemPickerBreakId = hovered_id;
21880
0
        g.DebugItemPickerActive = false;
21881
0
    }
21882
0
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
21883
0
        if (change_mapping && IsMouseClicked(mouse_button))
21884
0
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
21885
0
    SetNextWindowBgAlpha(0.70f);
21886
0
    if (!BeginTooltip())
21887
0
        return;
21888
0
    Text("HoveredId: 0x%08X", hovered_id);
21889
0
    Text("Press ESC to abort picking.");
21890
0
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
21891
0
    if (change_mapping)
21892
0
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
21893
0
    else
21894
0
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
21895
0
    EndTooltip();
21896
0
}
21897
21898
// [DEBUG] ID Stack Tool: update queries. Called by NewFrame()
21899
void ImGui::UpdateDebugToolStackQueries()
21900
58.4k
{
21901
58.4k
    ImGuiContext& g = *GImGui;
21902
58.4k
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21903
21904
    // Clear hook when id stack tool is not visible
21905
58.4k
    g.DebugHookIdInfo = 0;
21906
58.4k
    if (g.FrameCount != tool->LastActiveFrame + 1)
21907
58.4k
        return;
21908
21909
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
21910
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
21911
4
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
21912
4
    if (tool->QueryId != query_id)
21913
0
    {
21914
0
        tool->QueryId = query_id;
21915
0
        tool->StackLevel = -1;
21916
0
        tool->Results.resize(0);
21917
0
    }
21918
4
    if (query_id == 0)
21919
4
        return;
21920
21921
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
21922
0
    int stack_level = tool->StackLevel;
21923
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
21924
0
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
21925
0
            tool->StackLevel++;
21926
21927
    // Update hook
21928
0
    stack_level = tool->StackLevel;
21929
0
    if (stack_level == -1)
21930
0
        g.DebugHookIdInfo = query_id;
21931
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
21932
0
    {
21933
0
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
21934
0
        tool->Results[stack_level].QueryFrameCount++;
21935
0
    }
21936
0
}
21937
21938
// [DEBUG] ID Stack tool: hooks called by GetID() family functions
21939
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
21940
0
{
21941
0
    ImGuiContext& g = *GImGui;
21942
0
    ImGuiWindow* window = g.CurrentWindow;
21943
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21944
21945
    // Step 0: stack query
21946
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
21947
0
    if (tool->StackLevel == -1)
21948
0
    {
21949
0
        tool->StackLevel++;
21950
0
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
21951
0
        for (int n = 0; n < window->IDStack.Size + 1; n++)
21952
0
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
21953
0
        return;
21954
0
    }
21955
21956
    // Step 1+: query for individual level
21957
0
    IM_ASSERT(tool->StackLevel >= 0);
21958
0
    if (tool->StackLevel != window->IDStack.Size)
21959
0
        return;
21960
0
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
21961
0
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
21962
21963
0
    switch (data_type)
21964
0
    {
21965
0
    case ImGuiDataType_S32:
21966
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
21967
0
        break;
21968
0
    case ImGuiDataType_String:
21969
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
21970
0
        break;
21971
0
    case ImGuiDataType_Pointer:
21972
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
21973
0
        break;
21974
0
    case ImGuiDataType_ID:
21975
0
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
21976
0
            return;
21977
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
21978
0
        break;
21979
0
    default:
21980
0
        IM_ASSERT(0);
21981
0
    }
21982
0
    info->QuerySuccess = true;
21983
0
    info->DataType = data_type;
21984
0
}
21985
21986
static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
21987
0
{
21988
0
    ImGuiStackLevelInfo* info = &tool->Results[n];
21989
0
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
21990
0
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
21991
0
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
21992
0
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
21993
0
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
21994
0
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
21995
0
        return (*buf = 0);
21996
#ifdef IMGUI_ENABLE_TEST_ENGINE
21997
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
21998
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
21999
#endif
22000
0
    return ImFormatString(buf, buf_size, "???");
22001
0
}
22002
22003
// ID Stack Tool: Display UI
22004
void ImGui::ShowIDStackToolWindow(bool* p_open)
22005
0
{
22006
0
    ImGuiContext& g = *GImGui;
22007
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
22008
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
22009
0
    if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
22010
0
    {
22011
0
        End();
22012
0
        return;
22013
0
    }
22014
22015
    // Display hovered/active status
22016
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
22017
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
22018
0
    const ImGuiID active_id = g.ActiveId;
22019
#ifdef IMGUI_ENABLE_TEST_ENGINE
22020
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
22021
#else
22022
0
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
22023
0
#endif
22024
0
    SameLine();
22025
0
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
22026
22027
    // CTRL+C to copy path
22028
0
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
22029
0
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
22030
0
    SameLine();
22031
0
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
22032
0
    if (tool->CopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused))
22033
0
    {
22034
0
        tool->CopyToClipboardLastTime = (float)g.Time;
22035
0
        char* p = g.TempBuffer.Data;
22036
0
        char* p_end = p + g.TempBuffer.Size;
22037
0
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
22038
0
        {
22039
0
            *p++ = '/';
22040
0
            char level_desc[256];
22041
0
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
22042
0
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
22043
0
            {
22044
0
                if (level_desc[n] == '/')
22045
0
                    *p++ = '\\';
22046
0
                *p++ = level_desc[n];
22047
0
            }
22048
0
        }
22049
0
        *p = '\0';
22050
0
        SetClipboardText(g.TempBuffer.Data);
22051
0
    }
22052
22053
    // Display decorated stack
22054
0
    tool->LastActiveFrame = g.FrameCount;
22055
0
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
22056
0
    {
22057
0
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
22058
0
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
22059
0
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
22060
0
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
22061
0
        TableHeadersRow();
22062
0
        for (int n = 0; n < tool->Results.Size; n++)
22063
0
        {
22064
0
            ImGuiStackLevelInfo* info = &tool->Results[n];
22065
0
            TableNextColumn();
22066
0
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
22067
0
            TableNextColumn();
22068
0
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
22069
0
            TextUnformatted(g.TempBuffer.Data);
22070
0
            TableNextColumn();
22071
0
            Text("0x%08X", info->ID);
22072
0
            if (n == tool->Results.Size - 1)
22073
0
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
22074
0
        }
22075
0
        EndTable();
22076
0
    }
22077
0
    End();
22078
0
}
22079
22080
#else
22081
22082
void ImGui::ShowMetricsWindow(bool*) {}
22083
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
22084
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
22085
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
22086
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
22087
void ImGui::DebugNodeFont(ImFont*) {}
22088
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
22089
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
22090
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
22091
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
22092
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
22093
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
22094
22095
void ImGui::ShowDebugLogWindow(bool*) {}
22096
void ImGui::ShowIDStackToolWindow(bool*) {}
22097
void ImGui::DebugStartItemPicker() {}
22098
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
22099
22100
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
22101
22102
//-----------------------------------------------------------------------------
22103
22104
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
22105
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
22106
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
22107
#include "imgui_user.inl"
22108
#endif
22109
22110
//-----------------------------------------------------------------------------
22111
22112
#endif // #ifndef IMGUI_DISABLE